开发者

sort a dictionary according to their values in python [duplicate]

开发者 https://www.devze.com 2023-01-08 18:23 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Sort by key of dictionary inside a dictionary in Python
This question already has answers here: Closed 12 years ago.

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'])
0

精彩评论

暂无评论...
验证码 换一张
取 消