-1

I have a dictionary which has some dictionaries inside. Like this:

Dict= {
"Item1": {"price": 73814.55, "date": f_actual}, 
"Item2": {"price": 75700, "date": f1},
"Item3": {"price": 84200, "date": f2}
}

I want to sort the attribute 'price' (from highest to lowest). I think I can use sorted function but I dont know how to refer to ´price´ key since they are nested to Item1, Item2, etc:

sorted(Dict, key = ??, reverse = True)

So, my question is how can I do this? Is there any other approach?

Newbie
  • 451
  • 1
  • 3
  • 14

3 Answers3

4

I would do it this way:

sorted(Dict.items(), key=lambda x: x[1].get('price'), reverse=True)

Please note that ordering makes sense for lists object, but it doesn't for dictionaries, since they are basically HashMaps.

So in this way you will have an ordered list of tuples (key, value), but if you want to go back to a dictionary preserving an order that doesn't make much sense.

Please also give a look at this answer here: How do I sort a dictionary by value?

Hammond95
  • 556
  • 7
  • 20
  • 2
    +1 to you. A little cosmetic change to your solution is suggested. You can recreate the dictionary by "print(dict(sorted(Dict.items(), key=lambda x:x[1].get('price'), reverse=True)))" – Amit Dec 17 '20 at 17:44
0

I am sure there is an elegant way. Just wait for somebody to give a cleaner/faster solution. In the meanwhile ...

print([Dict[i] for i in sorted(Dict, key=lambda item: Dict[item]["price"], reverse=True)])

Gives the output as below

[{'price': 84200, 'date': 'f2'}, {'price': 75700, 'date': 'f1'}, {'price': 73814.55, 'date': 'f_actual'}]
Amit
  • 2,018
  • 1
  • 8
  • 12
0

This will do the trick for you

Dict= {
"Item1": {"price": 73814.55, "date": f_actual}, 
"Item2": {"price": 75700, "date": f1},
"Item3": {"price": 84200, "date": f2}
}

print(sorted(Dict.items(), key=lambda x: x[1]["price"], reverse=True))

[('Item3', {'price': 84200, 'date': 'f2'}), ('Item2', {'price': 75700, 'date': 'f1'}), ('Item1', {'price': 73814.55, 'date': 'f_actual'})]
sa_n__u
  • 336
  • 1
  • 9