gpt4 book ai didi

python - 比较具有较少循环的字典

转载 作者:行者123 更新时间:2023-11-28 19:46:51 26 4
gpt4 key购买 nike

我有一本字典,它的值是字典。以下是我的字典结构

myD = {'key1': {'x' : 123, 'y' : 432},
'key2': {'x' : 456, 'y' : 565},
'key3': {'x' : 789, 'y' : 420},
...}

我需要比较这个字典的值(如你所见,我在每个值中都有相似的字典结构)并生成以下输出。策略是遍历值字段中的每个字典并选择给定键的最小值并将其插入到新字典中。例如,如果我们考虑值字典中的 x 键,它的最小值是 123。所以我的新字典应该有 x:123

my_newD =  {'x' : 123, 'y' : 420, ...}

我可以使用 3 个 for 循环来实现这一点,但是有什么优雅的方法可以用更少的 for 循环来做到这一点吗?

最佳答案

这是一个使用 collections.defaultdict 的 O(n) 解决方案:

from collections import defaultdict

myD = {'key1': {'x' : 123, 'y' : 432},
'key2': {'x' : 456, 'y' : 565},
'key3': {'x' : 789, 'y' : 420}}

# initialise defaultdict of lists
d = defaultdict(list)

# iterate input dictionary and add values to lists
for v1 in myD.values():
for k2, v2 in v1.items():
d[k2].append(v2)

# calculate minimum
res = {k: min(v) for k, v in d.items()}

print(res)

{'x': 123, 'y': 420}

关于python - 比较具有较少循环的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50971429/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com