1

I have the following dictionary:

{1: (8, 3), 0: (8, 0), 2: (2, 3), 3: (2, 0)}

I would like to sort it by the tuple key and then by the key of the dictionary so the above will be:

 [{1: (2, 3), 3: (2, 0),0: (8, 3), 1: (8, 0)}]

I wrote the following:

result_list = sorted(codebook.items(), key= lambda item: item[1][0])

This sort by the tuple key but not afterwards by the dictionary key.

How can I do it?

Dejell
  • 13,947
  • 40
  • 146
  • 229
  • 2
    Your output would be a list, not a dictionary; dictionaries are unordered. – Martijn Pieters Jan 08 '14 at 18:17
  • Its a little unclear what you're trying, but if you're trying to sort the dictionary, stop, it cannot be done. Dictionaries in python are not sorted (and cannot be sorted) – wnnmaw Jan 08 '14 at 18:17
  • 4
    Also, your sample dictionary has two keys that are the same. This can't possibly be correct. –  Jan 08 '14 at 18:18
  • possible duplicate of [Sorting a Python list by two criteria](http://stackoverflow.com/questions/5212870/sorting-a-python-list-by-two-criteria) – Ashwini Chaudhary Jan 08 '14 at 18:18
  • I fixed my question there is already a correct answer to accept i – Dejell Jan 08 '14 at 18:22

1 Answers1

5
sorted(codebook.items(), key= lambda item: (item[1][0],item[0]))

this will sort first by the first item in the tuple then by the dictionary key

just to clarify a few things for OP

  • Dictionaries are not sortable, so you cannot ever have a "sorted" dictionary

    • (there is a OrderedDictionary, but its essentially the same as a NamedTuple, both of these containers do have an order)
  • This will return a list of tuples not a dictionary. the return will look like

    [(dictionary_key,(tuple,values)),(dictionary_key,(tuple,values),...]

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179