Sorting dictionaries
sorted(iterable[, key][, reverse])
Return a new sorted list from the items in iterable.
key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).
items()
Return a new view of the dictionary’s items (key, value) pairs.
The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.
>>> dict = {1: {'s': 3} , 2: {'x': 4}, 3: {'c': 0}}
>>> dict.items()
dict_items([(1, {'s': 3}), (2, {'x': 4}), (3, {'c': 0})])>> type(dict.items())
<class 'dict_items'>>>> for i,v in dict.items():
... print(i,v)
...
1 {'s': 3}
2 {'x': 4}
3 {'c': 0}
>>> for i in dict.items():
... print(i)
...
(1, {'s': 3})
(2, {'x': 4})
(3, {'c': 0})
By default it sorts on the key:
>>> for i,v in sorted(dict.items(), key= lambda x: x[0]):
... print(i,v)
...
1 {'s': 3}
2 {'x': 4}
3 {'c': 0}
which would be the same as
>> for i,v in sorted(dict.items()):
... print(i,v)
What about sorting alphabetically the cities in {'Asia': {'India': ['Bangalore'], 'China':['Shanghai']}
for i,j in sorted(locations['Asia'].items(), key=lambda x: x[1]):
print(j[0],i)