1

I have a dictionary that contains the following info:

my_dict = {
'key1' : ['f', 'g', 'h', 'i', 'j'],
'key2' : ['b', 'a', 'e', 'f', 'k'],
'key3' : ['a', 'd', 'c' , 't', 'z'],
'key4' : ['a', 'b', 'c', 'd', 'e']
}

I want to know how can I sort the printed result in alphabetical order using the index 0 of the list. If index 0 of two lists are the same, it will consider in sorting the next index which is index 1.

The output should look like this:

Officer 'a', 'b' with 'key4' ate 'c' with 'd' and 'e'.
Officer 'a', 'd' with 'key3' ate 'c' with 't' and 'z'.
Officer 'b', 'a' with 'key2' ate 'e' with 'f' and 'k'.
Officer 'f', 'g' with 'key1' ate 'h' with 'i' and 'j'.
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195

1 Answers1

4

Just sort the dictionary items by value:

>>> import operator
>>>
>>> for key, value in sorted(my_dict.items(), key=operator.itemgetter(1)):
...     print("Officer '{1}', '{2}' with '{0}' ate '{3}' with '{4}' and '{5}'.".format(key, *value))
... 
Officer 'a', 'b' with 'key4' ate 'c' with 'd' and 'e'.
Officer 'a', 'd' with 'key3' ate 'c' with 't' and 'z'.
Officer 'b', 'a' with 'key2' ate 'e' with 'f' and 'k'.
Officer 'f', 'g' with 'key1' ate 'h' with 'i' and 'j'.
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Hey alecxe! One question: Why did you use 1 inside itemgetter()? – Juan dela Cruz Sep 27 '15 at 01:02
  • @JuandelaCruz this is because `items()` would give you tuples where the first element (with 0 index) is a key and the second (with index 1) is a value. This way we are asking `sorted()` to use the dictionary values as a sorting key. See also: http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value. Hope that helps. – alecxe Sep 27 '15 at 01:19