how.wtf

Sort a dictionary by key or value in Python

· Thomas Taylor

Sorting based on a dictionary value or key is easy using Python.

Sort by value in a dictionary

In Python 3.7 and above, a combination of dictionary comprehension and sorted can be used:

1foo = {"first": 1, "third": 3, "second": 2, "zeroth": 0}
2print({k: v for k, v in sorted(foo.items(), key=lambda i: i[1])})

In addition,

1foo = {"first": 1, "third": 3, "second": 2, "zeroth": 0}
2print(dict(sorted(foo.items(), key=lambda i: i[1])))

Output:

1{'zeroth': 0, 'first': 1, 'second': 2, 'third': 3}

sorted allows a optional keyword argument of key: a function to execute for ordering.

Sort by key in a dictionary

Similar to the technique before, the lambda argument can reference the 0th index to sort by the dictionary keys.

1foo = {"first": 1, "third": 3, "second": 2, "zeroth": 0}
2print({k: v for k, v in sorted(foo.items(), key=lambda i: i[0])})

Output:

1{'first': 1, 'second': 2, 'third': 3, 'zeroth': 0}

#python  

Reply to this post by email ↪