-3

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}}
Sociopath
  • 13,068
  • 19
  • 47
  • 75

2 Answers2

1

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"]))
qmeeus
  • 2,341
  • 2
  • 12
  • 21
  • 2
    Yes, assuming python>3.6: https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6 – qmeeus Jul 17 '20 at 07:15
1

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'})])
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
  • You just copy/paste my answer, add an OrderedDict (which is useless for py3.6+) and claim it yours? – qmeeus Jul 17 '20 at 07:43
  • Relax sir, I did not copy your answer, your answer is specifically for Python 3.x where as mine covers both Python 2.x and 3.x. cheers – DirtyBit Jul 17 '20 at 08:00