简体   繁体   English

根据单独的值匹配查找字典中的最小值

[英]Find lowest value in dict of dicts based on separate value match

I have a dict of dicts.我有一个字典。 I want to find top-level keys based on uniqueness of one value or minimum of another.我想根据一个值的唯一性或另一个值的最小值来查找顶级键。

Example:例子:

d = {'first': {'key_to_match': 'a', 'key_to_compare': 50}, 
'second': {'key_to_match': 'b', 'key_to_compare': 50}, 
'third': {'key_to_match': 'a', 'key_to_compare': 10}}

I want the keys of each dict with the lowest key_to_compare for each key_to_match.我想要每个 key_to_match 的 key_to_compare 最低的每个字典的键。 In this case, ['second', 'third'].在这种情况下,['第二','第三']。

I have tried turning them into a list of tuples and comparing that way but that seems needlessly convoluted.我曾尝试将它们变成元组列表并以这种方式进行比较,但这似乎不必要地令人费解。

Here is an example.这是一个例子。

d = {
    'first': {'key_to_match': 'a', 'key_to_compare': 50}, 
    'second': {'key_to_match': 'b', 'key_to_compare': 50}, 
    'third': {'key_to_match': 'a', 'key_to_compare': 10}
}

# Output format: {'a': {'key': 'first', 'value': 50}}
lowest_keys = {}
for k, v in d.items():
    s_key = v['key_to_match']
    s_value = v['key_to_compare']
    if not lowest_keys.get(s_key) or lowest_keys[s_key]['value'] > s_value:
        lowest_keys[s_key] = {'key': k, 'value': s_value}

print(lowest_keys)
print([v['key'] for v in lowest_keys.values()])

I tried to make it readable.我试图让它可读。 Processed values are saved in lowest_keys dictionary as the loop progresses.随着循环的进行,处理的值保存在lowest_keys字典中。 It keeps in memory the top level key ('first', 'second' etc.), sub key group ('key_to_match') and the lowest found value so far ('key_to_compare').它在 memory 中保留了顶级密钥('first'、'second'等)、子密钥组('key_to_match')和迄今为止找到的最低值('key_to_compare')。 If the loop encounters a lower value from the same group, it saves the value and top key in a dict.如果循环遇到来自同一组的较低值,它将值和顶部键保存在字典中。 The last print shows how you can access this data.最后的print显示了如何访问这些数据。

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

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