Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
Using pprint() to print dictionaries while preserving their key order#
While parsing a CSV file using csv.DictReader today I noticed the following surprising result:
1import csv2from io import StringIO3from pprint import pprint4
5csv_content = """id,name,latitude,longitude,country6nyc,New York City,40.7128,-74.006,US7lon,London,51.5074,-0.1278,GB8tok,Tokyo,35.6895,139.6917,JP"""9
10rows = list(csv.DictReader(StringIO(csv_content)))11pprint(rows)This output the following:
1[{'country': 'US',2 'id': 'nyc',3 'latitude': '40.7128',4 'longitude': '-74.006',5 'name': 'New York City'},6 {'country': 'GB',7 'id': 'lon',8 'latitude': '51.5074',9 'longitude': '-0.1278',10 'name': 'London'},11 {'country': 'JP',12 'id': 'tok',13 'latitude': '35.6895',14 'longitude': '139.6917',15 'name': 'Tokyo'}]I had expected DictReader() to preserve the order of keys from the CSV file, since Python has defaulted to ordered dictionaries for a while now.
It turns out DictReader() does do that… but pprint() does not! From the pprint documentation:
pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False)
Note that sort_dicts defaults to True, presumably for historical reasons.
So the following does what I had expected in the first place:
1pprint(rows, sort_dicts=False)Output:
1[{'id': 'nyc',2 'name': 'New York City',3 'latitude': '40.7128',4 'longitude': '-74.006',5 'country': 'US'},6 {'id': 'lon',7 'name': 'London',8 'latitude': '51.5074',9 'longitude': '-0.1278',10 'country': 'GB'},11 {'id': 'tok',12 'name': 'Tokyo',13 'latitude': '35.6895',14 'longitude': '139.6917',15 'country': 'JP'}]