sort dictionary in python by key code example
Example 1: how to sort a dictionary by value in python
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
Example 2: sort dictionary by key
sortedDictionary = sorted(mydictionary.keys())
Example 3: filter dict by list of keys python
dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys }
Example 4: sort dictionary by key
dictionary_items = a_dictionary.items()
sorted_items = sorted(dictionary_items)