If you use [some dict].items()
, it produces a list of tuples:
>>> d={3:'three',35:'thirty five',100:'one hindred'}
>>> d
{35: 'thirty five', 3: 'three', 100: 'one hindred'}
>>> d.items()
[(35, 'thirty five'), (3, 'three'), (100, 'one hindred')]
Tuples are sortable in Python:
>>> sorted(d.items())
[(3, 'three'), (35, 'thirty five'), (100, 'one hindred')]
Therefore, your dictionary sorts just as you desire with Python's default sort order:
>>> lettersandnumbers = {'Z': 1, 'Y': 0, 'X': 1, 'W': 17, 'V': 4, 'U': 0,'T': 22, 'S': 21, 'R': 31, 'Q': 0, 'P': 12, 'O': 8,'N': 10, 'M': 29, 'L': 27, 'K': 14, 'J': 51, 'I': 7,'H': 14, 'G': 21, 'F': 12, 'E': 27, 'D': 40, 'C': 43,'B': 28, 'A': 34}
>>> sorted(lettersandnumbers.items())
[('A', 34), ('B', 28), ('C', 43), ('D', 40), ('E', 27), ('F', 12), ('G', 21), ('H', 14), ('I', 7), ('J', 51), ('K', 14), ('L', 27), ('M', 29), ('N', 10), ('O', 8), ('P', 12), ('Q', 0), ('R', 31), ('S', 21), ('T', 22), ('U', 0), ('V', 4), ('W', 17), ('X', 1), ('Y', 0), ('Z', 1)]
(You may need to use sorted's key
parameter if the desired order is different that the default. In the case, the default works.)
Then if you want a dict that keeps this order:
>>> from collections import OrderedDict
>>> od=OrderedDict(sorted(lettersandnumbers.items()))
>>> od.items()[0]
('A', 34)
>>> od.items()[-1]
('Z', 1)
But ordered dict is based on insertion order, so it will be unsorted if you add anything that is not in sort order.
Better still, avoid the making an unnecessary copy of the dict, and just iterate on the dict as needed in the then current sort order:
for k,v in sorted(d.items()):
# deal with the key and value in sorted order at that moment...
With Python 2, you need to use d.iteritems() or you will produce 2 temp lists: 1 for the items and 1 to sort. With Py 3 (or with Py 2 and d.iteritems() method) only 1 temp list is produced for the sort.