I have a Dictionary like
{'A': {'frequency': 4}, 'B': {'frequency': 2}, 'C': {'frequency': 7}}
How would I be able to sort this by the "frequency"
attribute?
I have a Dictionary like
{'A': {'frequency': 4}, 'B': {'frequency': 2}, 'C': {'frequency': 7}}
How would I be able to sort this by the "frequency"
attribute?
sorted(a, key=lambda x: (a[x]['frequency']))
To keep it ordered by request from the comments:
from collections import OrderedDict
OrderedDict(sorted(a.items(), key=lambda x: x[1]['frequency']))
dictionaries are not order in python. if you need to order the dictionary . better to use OrderedDict from collections modules
In [24]: from collections import OrderedDict
...: d = {'A': {'frequency': 4}, 'B': {'frequency': 2}, 'C': {'frequency': 7}}
...:
...: ord_a = OrderedDict(sorted(ord_d.items(), key = lambda x: x[1]['frequency']))
...:
...:
In [25]:
In [25]: print(ord_a)
OrderedDict([('B', {'frequency': 2}), ('A', {'frequency': 4}), ('C', {'frequency': 7})])