Sort dictionary by key and value in Python

Renesh Bedre    2 minute read

Python dictionary

  • Python dictionary is a built-in data type that can be used for storing data as keys: value format. Each key is unique, hashable, and has its own value in the dictionary.
  • Python dictionary is indexed by keys. In the dictionary, keys are unique and immutable (you can not modify them). The strings or numbers can be used as keys. The list or dictionary can not be used as keys as they are mutable.
  • Python dictionary can be created using dict() constructor, dict comprehension, or by using the pair of curly braces {}. The comma-separated keys: value can be provided in curly braces for creating a dictionary.
  • The Python dictionary is mutable (it can be updated) and unordered

Create Python dictionary

Create dictionary using dict() constructor,

# Python 3.10
x = dict(Texas=1, Florida=2, Arizona=3)
x
# output
{'Texas': 1, 'Florida': 2, 'Arizona': 3}

Create dictionary using paired curly braces {},

y = {'Texas': 1, 'Florida': 2, 'Arizona': 3}
y
# output
{'Texas': 1, 'Florida': 2, 'Arizona': 3}

Create dictionary using dict comprehensions (based on iterables),

z = {val: i for i, val in enumerate(('Texas', 'Florida', 'Arizona'))}
z
# output
{'Texas': 0, 'Florida': 1, 'Arizona': 2}

Sort Python dictionary by key

To sort dictionary by key, you can use `sorted()` function using for loop or `sorted()` using dict `items()` function.

The sorted function syntax: sorted(iterable, key, reverse). It takes three input parameters. The iterable is a required parameter and can be dict, list, tuple, or any other iterator. The key and reverse are optional parameters. The key is useful for sorting purposes and reverse decides the order of sorting.

Here you will see the example of a sorted() function using for loop for sorting Python dictionary by key. By default, the dictionary keys will be sorted in ascending order. If you want to sort in descending order, set the parameter reverse=True

for key in sorted(x):
  print("key:",  key, "value:", x[key])
# output
key: Arizona value: 3
key: Florida value: 2
key: Texas value: 1

# sort in reverse order 
for key in sorted(x, reverse=True):
  print("key:",  key, "value:", x[key])
# output  
key: Texas value: 1
key: Florida value: 2
key: Arizona value: 3

sorted() using dict items() function,

sorted(x.items())
# output (return list)
[('Arizona', 3), ('Florida', 2), ('Texas', 1)]

# return as dictionary
dict(sorted(x.items()))
# output
{'Arizona': 3, 'Florida': 2, 'Texas': 1}

# sort in reverse order
dict(sorted(x.items(), reverse=True))
# output
{'Texas': 1, 'Florida': 2, 'Arizona': 3}

Sort Python dictionary by value

Here you will use the sorted() function to sort the dictionary by value

sorted(x.items(), key=lambda v: v[1])
# output
[('Texas', 1), ('Florida', 2), ('Arizona', 3)]

# return as dictionary
dict(sorted(x.items(), key=lambda v: v[1]))
# output
{'Texas': 1, 'Florida': 2, 'Arizona': 3}

# sort in reverse order
dict(sorted(x.items(), key=lambda v: v[1], reverse=True))
# output
{'Arizona': 3, 'Florida': 2, 'Texas': 1}

The lambda function passes the dictionary values instead of keys for sorting.

Enhance your skills with courses on Python and pandas

References

This work is licensed under a Creative Commons Attribution 4.0 International License

Some of the links on this page may be affiliate links, which means we may get an affiliate commission on a valid purchase. The retailer will pay the commission at no additional cost to you.

Tags:

Updated: