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?

5
  • 2
    Your output would be a list, not a dictionary; dictionaries are unordered. Commented Jan 8, 2014 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) Commented Jan 8, 2014 at 18:17
  • 4
    Also, your sample dictionary has two keys that are the same. This can't possibly be correct. Commented Jan 8, 2014 at 18:18
  • possible duplicate of Sorting a Python list by two criteria Commented Jan 8, 2014 at 18:18
  • I fixed my question there is already a correct answer to accept i Commented Jan 8, 2014 at 18:22

1 Answer 1

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),...]

Sign up to request clarification or add additional context in comments.

7 Comments

I'm also curious about the -1. +1 to make up for it.
I'm not the -1, but this answer doesn't produce the OP's desired result, a list containing one sorted dict. In fact, no answer possibly can.
It's exactly what I wanted - to sort the dictionary
meh thats based on the authors incorrect wording of his desired solution ... I think this answers what he actually was asking
@Dejel , one cannot sort a dictionary, and that isn't what this answer does. I'm glad you found an answer the works for you, but I'm concerned that you are still confused about what this does.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.