0

I have a dictionary that looks like this:

D={'CA':[1,2], 'AZ':[5,2], 'NY':[2,7]}

I want to sort this by the 1st element in the value list in descending order, which should end up like this:

D={'AZ':[5,2], 'NY':[2,7], 'CA':[1,2]}

How do I do it?

chu1688
  • 31
  • 1
  • 2
  • 1
    Dictionaries aren't ordered, you can't sort them. – Barmar Jan 28 '16 at 01:30
  • See the referenced duplicate question. Lists sort naturally in the order you want, so you can trivially adapt that answer for your needs. – Prune Jan 28 '16 at 01:40

1 Answers1

1

You can't really sort a dictionary, but you can get its keys in the sorted order that you described, and use that to make a sorted list of tuples:

sorted_keys = sorted(D, key = D.get, reverse = True)
#equivalently
sorted_keys = sorted(D, key = lambda x: D[x], reverse = True)
print [(key, D[key]) for key in sorted_keys]
#sort by 2 element
sorted_keys = sorted(D, key = lambda x: D[x][1], reverse = True)        

Output:

[('AZ', [5, 2]), ('NY', [2, 7]), ('CA', [1, 2])]

Garrett R
  • 2,687
  • 11
  • 15