gpt4 book ai didi

python - 将字典列表转换为唯一的字典

转载 作者:太空宇宙 更新时间:2023-11-03 10:49:58 25 4
gpt4 key购买 nike

我有:

[
{'id': 1, 'name': 'foo'},
{'id': 2, 'name': 'bar'},
{'id': 1, 'name': 'gesiel'}
]

我要:

{
1: [
{'id': 1, 'name': 'foo'},
{'id': 1, 'name': 'gesiel'}
],
2: [
{'id': 2, 'name': 'bar'}
]
}

此代码执行此操作:

organized = {d['id']:[] for d in data}
[organized[d['id']].append(d) for d in data]

是否有更 pythonic 的方法来做到这一点?

最佳答案

使用collections.defaultdict :

from collections import defaultdict

data = [{'id': 1, 'name': 'foo'}, {'id': 2, 'name': 'bar'}, {'id': 1, 'name': 'gesiel'}]

d = defaultdict(list)

for x in data:
d[x['id']].append(x)

print(d)
# defaultdict(<class 'list'>, {1: [{'id': 1, 'name': 'foo'}, {'id': 1, 'name': 'gesiel'}], 2: [{'id': 2, 'name': 'bar'}]})

关于python - 将字典列表转换为唯一的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52679704/

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