sort a dictionary according to their values in python [duplicate]
Possible Duplicate:
Sort by key of dictionary inside a dictionary in Python
I have a dictionary:
d={'abc.py':{'map':'someMap','distance':11},
'x.jpg':{'map':'aMap','distance':2},....}
Now what I need is: I need to sort d
according to their distances?
I tried sorted(d.i开发者_开发百科tems(),key=itemgetter(1,2)
, but it's not working.
How can it be done?
You cannot (really) influence the order in which your dict keys appear. If you want to iterate over the sorted keys, you could for instance use
sorted(d.keys(), key=lambda x: d[x]['distance'])
A dictonary can't be sorted. So you have to convert your data to a list and sort this list. Maybe you convert your dict to a list of tuples (key, value) and sort then.
You can do it like this:
sorted(d.items(), key=lambda x:x[1]['distance'])
精彩评论