Need suggestion on how below data structure can be sorted based on 'popularity'?
Data_structure={0:{name:"xxx",popularity:100},1:{name:"yyy", popularity:90}}
Need suggestion on how below data structure can be sorted based on 'popularity'?
Data_structure={0:{name:"xxx",popularity:100},1:{name:"yyy", popularity:90}}
sorted
builtin function in python accepts a key
argument that expects a function. So basically, you can do that:
data = {0: {"name": "xxx", "popularity": 100},1: {"name":"yyy", "popularity":90}}
data = dict(sorted(data.items(), key=lambda t: t[1]["popularity"]))
Using OrderedDict
to cover both Python 2.x and Python 3.x:
from collections import OrderedDict
data = {0: {"name": "xxx", "popularity": 100}, 1: {"name":"yyy", "popularity":90}}
ordered_data = OrderedDict(sorted(data.items(), key=lambda i: i[1]['popularity']))
print(ordered_data)
OUTPUT:
OrderedDict([(1, {'popularity': 90, 'name': 'yyy'}), (0, {'popularity': 100, 'name': 'xxx'})])