gpt4 book ai didi

python - 按某个键的值对列表中的字典进行分组

转载 作者:行者123 更新时间:2023-12-02 18:22:08 24 4
gpt4 key购买 nike

我有一个包含这样的字典的列表:

d = [ {'key1': 1, 'key2': 10, 'key3': 0.75, 'key4':5},
{'key1': 2, 'key2': 20, 'key3': 0.6, 'key4':4},
{'key1': 3, 'key2': 10, 'key3': 0.8, 'key4':8
{'key1': 4, 'key2': 30, 'key3': 0.86, 'key4':2},
{'key1': 5, 'key2': 10, 'key3': 0.9, 'key4':7},
{'key1': 6, 'key2': 20, 'key3': 0.73, 'key4':3},
]

我想将 key2 中具有相同值的字典分组。像这样:

d10= [{'key1': 1, 'key2': 10, 'key3': 0.75, 'key4':5},
{'key1': 3, 'key2': 10, 'key3': 0.8, 'key4':8},
{'key1': 5, 'key2': 10, 'key3': 0.9, 'key4':7} ]

d20= [ {'key1': 2, 'key2': 20, 'key3': 0.6, 'key4':4},
{'key1': 6, 'key2': 20, 'key3': 0.73, 'key4':3} ]

d30=[ {'key1': 4, 'key2': 30, 'key3': 0.86, 'key4':2} ]

你能帮我吗?

最佳答案

这是使用 defaultdict 的一种方法:

from collections import defaultdict                                                            

res = defaultdict(list)

for obj in d:
key = obj['key2']
res[key].append(obj)

输出:

defaultdict(list,
{10: [{'key1': 1, 'key2': 10, 'key3': 0.75, 'key4': 5},
{'key1': 3, 'key2': 10, 'key3': 0.8, 'key4': 8},
{'key1': 5, 'key2': 10, 'key3': 0.9, 'key4': 7}],
20: [{'key1': 2, 'key2': 20, 'key3': 0.6, 'key4': 4},
{'key1': 6, 'key2': 20, 'key3': 0.73, 'key4': 3}],
30: [{'key1': 4, 'key2': 30, 'key3': 0.86, 'key4': 2}]})

关于python - 按某个键的值对列表中的字典进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70761905/

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