简体   繁体   中英

Sort dict by a dict value

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM