I am trying to sort a dictionary containing lists. For example, if I have this dictionary:
a = {'q': {3: [4, 2, 7]}, 'a': {1: [5, 45, 11]}, 'e': {23: [11, 45, 2]}}
I want the output after sorting to be:
[(e, {23:[11,45,2}]), (a, {1:[5,45,11]}), (q,{3,[4,2,7]})]
I am actually sorting in reverse, using the first item in the list as the key for the sort.
In the event that the first items of two lists are identical, like above, I sort for the string associated with the list (main key) in alphabetical order.
I am not sure if I can get the output of tuples with dictionary in it as I am sorting for that the list in that dictionary.
I have tried this code:
sorted((x,b.items(), key=lambda x:[1][2]) for x,b in a.items())
It raised an error for invalid syntax, and I can’t figure out what’s wrong.
Let’s break the problem in parts. You really want to sort the list
a.items(). So:Now, for each element in the list, you have a tuple of a value (
'q'etc.) and a dictionary. Presumably, each dictionary contains only one key, and you want to use the index-1 element of each dictionary’s value as the primary key. So, the key for the first element should be:to_sort[0][1].values()[0][1]:to_sort[0][1]gives you the dictionary{3: [4, 2, 7]},.values()gives you the list[[4, 2, 7]], and[0][1]on that gives you2. The secondary sort key is simplyto_sort[0].So we get:
We are almost there. Now you just need to tell sort that you want reversed output:
Is this what you want?
If you want a one-liner, you can do: