gpt4 book ai didi

python - 在 for 循环中将值附加到字典

转载 作者:行者123 更新时间:2023-12-04 23:39:36 26 4
gpt4 key购买 nike

只是不能得到这个工作。任何帮助都受到高度赞赏。

dict = {}
for n in n1:
if # condition #
dict[key] = []
dict[key].append(value)
print dict

这是打印这样的东西

{'k1':['v1']} and {'k1':['v2']}



我在这段代码中几乎没有其他嵌套的 for 循环,它们将使用这个 dict 并且该 dict 只有最新的键值对,即 {'k1':'v2'}
我正在寻找类似 {'k1':['v1','v2']} 的东西

请在不使用 setdefault 的情况下提出解决方案

最佳答案

collections.defaultdict一试:

#example below is in the docs.
from collections import defaultdict

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
d[k].append(v)

print(sorted(d.items()))
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
d = defaultdict(list)行默认将键值设置为空字典,并将值附加到循环中的列表中。

关于python - 在 for 循环中将值附加到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41970992/

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