Dictionary content sorting

How can we show dictionary content(Key & Values) in sorted order in python. I am aware that using sorted function we can show either keys or values in sorted order but how can we show both as result either sorted based on keys or values.

Extract the items() (which has both keys and values) and sort by whichever one you want?

>>> d = {"color": "red", "flower": "aster", "animal": "zebra"}
# sort by keys
>>> sorted(d.items(), key=lambda x: x[0])
[('animal', 'zebra'), ('color', 'red'), ('flower', 'aster')]
# sort by values
>>> sorted(d.items(), key=lambda x: x[1])
[('flower', 'aster'), ('color', 'red'), ('animal', 'zebra')]
1 Like

To show a dict sorted by key:

for key in sorted(mydict):
    print(key, mydict[key])

To show a dict sorted by both key (first) and then value (in the case of
a tie, which will be very rare and unusual):

for key, value in sorted(mydict.items()):
    print(key, value)

Ties will be very unusual because keys must be unique in a dict. The
only way to get a tie would be if keys A and B compare as equal, but
have different hashes. So in practical terms, this is equivalent to just
sorted by key.

To show a dict sorted by value:

for key in sorted(mydict, key=lambda k: mydict[k]):
    print(key, mydict[key])

or if you prefer:

for key, value in sorted(mydict.items(), key=lambda t: t[1]):
    print(key, value)
>>> d = {"color": "red", "flower": "aster", "animal": "zebra"}
>>> import pprint
>>> pprint.pprint(d)  # sorted by key.
{'animal': 'zebra', 'color': 'red', 'flower': 'aster'}
>>> pprint.pprint(d, sort_dicts=False)  # insertion order
{'color': 'red', 'flower': 'aster', 'animal': 'zebra'}

Thank you so much for quick and accurate response!

This would brake Python’s contract for hashable objects (Glossary — Python 3.12.1 documentation):

Hashable objects which compare equal must have the same hash value.

So this won’t happen for anything supplied by Python itself, especially for strings.