





Suppose you have a piggy bank containing a lot of coins and you want to count them. You store your coins in a dictionary. Once you finish adding them in the dictionary, you want to know how much you have of each denomination. How do you do it?
To see this example in real life in Python, let’s create the dictionary.
>>> coins = {"penny":20, "nickel":5, "dime":30, "quarter":10}
To print out the denomination, we can use the for loop.
>>> for key, value in coins.iteritems():
... print(key, value)
...
('quarter', 10)
('penny', 20)
('nickel', 5)
('dime', 30)
What if you want them sorted by the denomination? You can do so using the sorted function.
>>> for key, value in sorted(coins.iteritems()):
... print(key, value)
...
('dime', 30)
('nickel', 5)
('penny', 20)
('quarter', 10)
The sorting takes place right away and you don’t need to run another function which is very convenient.
If you use Python 3.x, use items() rather than iteritems() since iteritems() has been deprecated.
>>> for key, value in sorted(coins.items()):
... print(key, value)
...
('dime', 30)
('nickel', 5)
('penny', 20)
('quarter', 10)
If you want to iterate over item one by one, you can do that too.
>>> count = iter(sorted(coins.iteritems()))
>>> count.next()
('dime', 30)
>>> count.next()
('nickel', 5)
>>> count.next()
('penny', 20)
This is a handy feature if you want to go through them one by one.
If you just want to sort the dictionary and not print them one by one, you can do that too.
>>> print sorted(coins.items())
[('dime', 30), ('nickel', 5), ('penny', 20), ('quarter', 10)]
As you can see, there are many options to choose from.