gpt4 book ai didi

python - 创建每个键有多个值的字典

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

如何从 2 个列表中为每个键创建一个具有多个值的字典?

例如,我有:

>>> list1 = ['fruit', 'fruit', 'vegetable']

>>> list2 = ['apple', 'banana', 'carrot']

而且,我想要一些效果:

>>> dictionary = {'fruit': ['apple', 'banana'], 'vegetable': ['carrot']}

到目前为止,我已经尝试了以下方法:

>>> keys = list1
>>> values = list2
>>> dictionary = dict(zip(keys, values))
>>> dictionary
{'fruit': 'banana', 'vegetable': 'carrot'}

最佳答案

您可以使用 dict.setdefault 和一个简单的 for 循环:

>>> list1 = ["fruit", "fruit", "vegetable"]
>>> list2 = ["apple", "banana", "carrot"]
>>> dct = {}
>>> for i, j in zip(list1, list2):
... dct.setdefault(i, []).append(j)
...
>>> dct
{'fruit': ['apple', 'banana'], 'vegetable': ['carrot']}

来自docs :

setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

关于python - 创建每个键有多个值的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29405989/

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