Yassine Belmamoun Yassine Belmamoun - 4 years ago 119
Python Question

Order a dictionary based on specific values

Before writing a function, I would like to be sure there is no pre-built (optimized) solution (like sorted()) that can:

From a dictionary like this one :

tags = {'pinoyako':{'likes': 119, 'comments': 11, 'count': 1}, 'dii':{'likes': 151, 'comments': 3, 'count': 1},'djiphantom3':{'likes': 127, 'comments': 6, 'count': 1}}

Order the keys based on 'likes', 'comments' or 'count'. If it's based on 'likes', the output should be a list ordered :

output = [['dii',151],['djiphantom3',127],['pinoyako',119]]

Answer Source

Use a generator expression within sorted() function with a proper key function:

In [22]: from operator import itemgetter
In [23]: sorted(((k, v['likes']) for k, v in tags.items()), key=itemgetter(1), reverse=True)
Out[23]: [('dii', 151), ('djiphantom3', 127), ('pinoyako', 119)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download