0

How can we sort a dictionary in python using the internal state of the value?

For example:

myDict = {'a': {'day': [0, 1, 2, 5], 'week': [4, 3, 1, 2, 3]},
          'b': {'day': [0, 6, 2, 5], 'week': [4, 3, 1, 2, 3]}}

I want to sort the dictionary keys by the second value of the day list for their corresponding value dictionaries.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
Moriarty
  • 2,067
  • 2
  • 11
  • 13

1 Answers1

3

You can sort that like this

print sorted(myDict, key=lambda v: myDict[v]['day'][1])
# ['a', 'b']

The key parameter accepts a function which will be used to determine the value to be used for the current item during the sorting.

As sorted iterates over the myDict, we get each and every key. So, for each key, we pick the second element in the day dictionary and use it as the value which represents the key during sorting.

What we have done is, when sorting function looks for a value of a we return 1 and when it looks for b we return 6.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497