gpt4 book ai didi

python - 如何将列表中的值添加到字典中?

转载 作者:行者123 更新时间:2023-11-28 21:22:42 25 4
gpt4 key购买 nike

dict={}
i=["abc","def","ghi","jkl"]
j=[["a","b","c","d"],["q","w","e","r"],["t","y","u","i"]]
for item in i:
dict[item]=[str(j[item])]
print dict

输出应该是这样的

dict={"abc":["a","b","c","d"], "def":["q","w","e","r"] ...} 

如何在 python 中将列表添加到字典中?

最佳答案

使用 zip() function合并两个列表:

dict(zip(i, j))

演示:

>>> i=["abc","def","ghi","jkl"]
>>> j=[["a","b","c","d"],["q","w","e","r"],["t","y","u","i"]]
>>> dict(zip(i, j))
{'abc': ['a', 'b', 'c', 'd'], 'ghi': ['t', 'y', 'u', 'i'], 'def': ['q', 'w', 'e', 'r']}

zip() 将列表中的元素配对成元组序列; dict() 构造函数接受一系列元组并将它们解释为键值对。

关于python - 如何将列表中的值添加到字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18483315/

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