Sort dict by a dict value

Question:

I’m trying to sort a dict‘s value where the value is a dict where the value is a list of two integers. I’m trying to sort the rows in the inner dict by the first integer of the list.

This is the value of the dict:

{'EQUITY': {'CA': [15, 20], 'US': [25, 30]}, ... }

Here, the ‘US’ row should come before the ‘CA’ row after sorting.

This is what I’m currently trying:

dict(sorted(data.items(), key=lambda item: item[1][ ?? ], reverse=True))

how should I index into the inner dict from here ??

Thanks in advance for the help.

Asked By: Rohan Mittal

||

Answers:

You are almost there. Try the following, which uses dict comprehension and sorted with key parameter:

dct = {'EQUITY': {'CA': [15, 20], 'US': [25, 30]}, 'FUTURE': {'CA': [5, 5], 'US': [10, 2]}}

output = {k: dict(sorted(d.items(), key=lambda item: item[1][0], reverse=True)) for k, d in dct.items()}

print(output)
# {'EQUITY': {'US': [25, 30], 'CA': [15, 20]}, 'FUTURE': {'US': [10, 2], 'CA': [5, 5]}}

Here, each item of d.items() would be a tuple like ('CA', [15, 20]). Therefore, to sort by 15, you need item[1][0].

Answered By: j1-lee
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.