简体   繁体   English

按嵌套字典中的值对字典进行排序

[英]Sort a dictionary by values in a nested dictionary

I have dictionary like so:我有这样的字典:

   dic = {first_a : { first_b : {10, 2} } , second_a : {second_b : {13, 15} } [...] }

I would like to sort the nested dictionary according to the sum of x_a and y_a.我想根据 x_a 和 y_a 的总和对嵌套字典进行排序。 I can't get my head around this one, could someone provide an helping hand ?我无法理解这个问题,有人可以提供帮助吗? I have tried to use the sorted() function but wasn't able to find the right lambda function to use as key..我曾尝试使用 sorted() 函数,但无法找到正确的 lambda 函数用作键..

Assuming that you meant to have a dictionary like this:假设您打算拥有这样的字典:

data = {'a': {'b': {2, 10}}, 'c': {'d': {13, 15}}}

You can get what you want like this:你可以像这样得到你想要的:

sorted(data, key =lambda k: sum(*dic[k].values()), reverse=True)

However I don't consider this very readable.但是我不认为这非常具有可读性。 I would instead do:我会这样做:

def get_sum(k):
    vals, *_ = data[k].values()
    return sum(vals)

sorted(data, key=get_sum, reverse=True)

When I'm looking at code late at night, too many parentheses == too long to figure out what's happening.当我在深夜查看代码时,括号太多 == 太长而无法弄清楚发生了什么。

Note that I used values() because I didn't know if your inner keys were constant.请注意,我使用values()是因为我不知道您的内部键是否是常量。 If they were, life is even easier.如果是的话,生活就更简单了。 Note this operates on and sorts the keys .请注意,这是对键进行操作和排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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