views:

64

answers:

3

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.items(),key=itemgetter(1,2), but it's not working.

How can it be done?

+3  A: 

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.

Steven Mohr
+3  A: 

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'])
jellybean
+1  A: 

You can do it like this:

sorted(d.items(), key=lambda x:x[1]['distance'])
Philip