Python sort dictionary items by value then by key
-
20-12-2019 - |
Question
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?
Solution
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),...]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow