Reputation:
I would like to print a python dictionary to a file using PrettyPrinter (for human readability) but have the dictionary be sorted by key in the output file to further improve readability. So:
mydict = {'a':1, 'b':2, 'c':3}
pprint(mydict)
currently prints to
{'b':2,
'c':3,
'a':1}
I would like to PrettyPrint the dictionary but have it printed out sorted by key eg.
{'a':1,
'b':2,
'c':3}
What is the best way to do this?
Upvotes: 94
Views: 173003
Reputation: 422
def print_dict(d):
def quote(obj):
return f"'{obj}'" if isinstance(obj, str) else obj
keys = list(sorted(d.keys()))
pairs = [f"{quote(k)}: {quote(d[k])}" for k in keys]
return '{' + ', '.join(pairs) + '}'
Upvotes: -1
Reputation: 3764
Another short oneliner:
mydict = {'c': 1, 'b': 2, 'a': 3}
print(*sorted(mydict.items()), sep='\n')
Upvotes: 1
Reputation: 7724
Another alternative :
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> import json
Then with python2 :
>>> print json.dumps(mydict, indent=4, sort_keys=True) # python 2
{
"a": 1,
"b": 2,
"c": 3
}
or with python 3 :
>>> print(json.dumps(mydict, indent=4, sort_keys=True)) # python 3
{
"a": 1,
"b": 2,
"c": 3
}
Upvotes: 27
Reputation: 54117
Actually pprint seems to sort the keys for you under python2.5
>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
'b': 9,
'c': 8,
'd': 7,
'e': 6,
'f': 5,
'g': 4,
'h': 3,
'i': 2,
'j': 1,
'k': 0}
But not always under python 2.4
>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
'b': 9,
'c': 8,
'd': 7,
'e': 6,
'f': 5,
'g': 4,
'h': 3,
'i': 2,
'j': 1,
'k': 0}
>>>
Reading the source code of pprint.py (2.5) it does sort the dictionary using
items = object.items()
items.sort()
for multiline or this for single line
for k, v in sorted(object.items()):
before it attempts to print anything, so if your dictionary sorts properly like that then it should pprint properly. In 2.4 the second sorted() is missing (didn't exist then) so objects printed on a single line won't be sorted.
So the answer appears to be use python2.5, though this doesn't quite explain your output in the question.
Python3 Update
Pretty print by sorted keys (lambda x: x[0]):
for key, value in sorted(dict_example.items(), key=lambda x: x[0]):
print("{} : {}".format(key, value))
Pretty print by sorted values (lambda x: x[1]):
for key, value in sorted(dict_example.items(), key=lambda x: x[1]):
print("{} : {}".format(key, value))
Upvotes: 112
Reputation: 2725
An easy way to print the sorted contents of the dictionary, in Python 3:
>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> for key, value in sorted(dict_example.items()):
... print("{} : {}".format(key, value))
...
a : 3
b : 2
c : 1
The expression dict_example.items()
returns tuples, which can then be sorted by sorted()
:
>>> dict_example.items()
dict_items([('c', 1), ('b', 2), ('a', 3)])
>>> sorted(dict_example.items())
[('a', 3), ('b', 2), ('c', 1)]
Below is an example to pretty print the sorted contents of a Python dictionary's values.
for key, value in sorted(dict_example.items(), key=lambda d_values: d_values[1]):
print("{} : {}".format(key, value))
Upvotes: 18
Reputation: 61
I had the same problem you had. I used a for loop with the sorted function passing in the dictionary like so:
for item in sorted(mydict):
print(item)
Upvotes: 6
Reputation: 135
I wrote the following function to print dicts, lists, and tuples in a more readable format:
def printplus(obj):
"""
Pretty-prints the object passed in.
"""
# Dict
if isinstance(obj, dict):
for k, v in sorted(obj.items()):
print u'{0}: {1}'.format(k, v)
# List or tuple
elif isinstance(obj, list) or isinstance(obj, tuple):
for x in obj:
print x
# Other
else:
print obj
Example usage in iPython:
>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> printplus(dict_example)
a: 3
b: 2
c: 1
>>> tuple_example = ((1, 2), (3, 4), (5, 6), (7, 8))
>>> printplus(tuple_example)
(1, 2)
(3, 4)
(5, 6)
(7, 8)
Upvotes: 12
Reputation: 12829
The Python pprint
module actually already sorts dictionaries by key. In versions prior to Python 2.5, the sorting was only triggered on dictionaries whose pretty-printed representation spanned multiple lines, but in 2.5.X and 2.6.X, all dictionaries are sorted.
Generally, though, if you're writing data structures to a file and want them human-readable and writable, you might want to consider using an alternate format like YAML or JSON. Unless your users are themselves programmers, having them maintain configuration or application state dumped via pprint
and loaded via eval
can be a frustrating and error-prone task.
Upvotes: 15
Reputation: 129914
You could transform this dict a little to ensure that (as dicts aren't kept sorted internally), e.g.
pprint([(key, mydict[key]) for key in sorted(mydict.keys())])
Upvotes: 4