snippetpythonCriticalCanonical
How do I sort a dictionary by key?
Viewed 0 times
keyhowsortdictionary
Problem
How do I sort a dictionary by its keys?
Example input:
Desired output:
Example input:
{2:3, 1:89, 4:5, 3:0}Desired output:
{1:89, 2:3, 3:0, 4:5}Solution
Note: for Python 3.7+, see this answer
Standard Python dictionaries are unordered (until Python 3.7). Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a
The easiest way is to use
Never mind the way
Python 3
For Python 3 users, one needs to use the
Standard Python dictionaries are unordered (until Python 3.7). Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a
dict in a way that would preserve the ordering.The easiest way is to use
OrderedDict, which remembers the order in which the elements have been inserted:In [1]: import collections
In [2]: d = {2:3, 1:89, 4:5, 3:0}
In [3]: od = collections.OrderedDict(sorted(d.items()))
In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])Never mind the way
od is printed out; it'll work as expected:In [11]: od[1]
Out[11]: 89
In [12]: od[3]
Out[12]: 0
In [13]: for k, v in od.iteritems(): print k, v
....:
1 89
2 3
3 0
4 5Python 3
For Python 3 users, one needs to use the
.items() instead of .iteritems():In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5Code Snippets
In [1]: import collections
In [2]: d = {2:3, 1:89, 4:5, 3:0}
In [3]: od = collections.OrderedDict(sorted(d.items()))
In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])In [11]: od[1]
Out[11]: 89
In [12]: od[3]
Out[12]: 0
In [13]: for k, v in od.iteritems(): print k, v
....:
1 89
2 3
3 0
4 5In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5Context
Stack Overflow Q#9001509, score: 1318
Revisions (0)
No revisions yet.