Python Glossary Русский

all Python 3Dictionaries (dict)term

Sorting a dictionary

sorting

sorted(d.items()) sorts the pairs. key= sets the sorting criterion. The result is a list of tuples, or a new dictionary.

Syntax

sorted(d.items())  |  sorted(d.items(), key=lambda x: x[1])

sorted() hands back a list of tuples, not a dict; wrap it in dict() to get a dictionary again — insertion order is preserved since 3.7. There is no in-place sort for a dict at all, only building a new object. The default comparison starts with the keys, so mixed key types (int next to str) raise TypeError; to sort by descending value and break ties alphabetically, use a compound key like (-value, key).

Examples

d = {'banana': 3, 'apple': 1, 'cherry': 2}
print(sorted(d.items()))
# → [('apple', 1), ('banana', 3), ('cherry', 2)]
print(sorted(d.items(), key=lambda x: x[1]))
# → [('apple', 1), ('cherry', 2), ('banana', 3)]
print(sorted(d.keys()))
# → ['apple', 'banana', 'cherry']
print(dict(sorted(d.items())))
# → {'apple': 1, 'banana': 3, 'cherry': 2} (по ключу)
print(dict(sorted(d.items(), key=lambda x: x[1], reverse=True)))
# → {'banana': 3, 'cherry': 2, 'apple': 1} (по значению убыв.)
print(sorted(d, key=d.get))
# → ['apple', 'cherry', 'banana']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy