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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41970992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:59:21  来源:igfitidea点击:

appending values to dictionary in for loop

python

提问by Krishna Chaitanya

Just cant get this working. Any help is highly appreciated.

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

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

This is printing something like this

这是打印这样的东西

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

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

I have few other nested for loops down this code, which will be using this dict and the dict has only the latest key value pairs i.e. {'k1':'v2'}

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

I am looking for something like {'k1':['v1','v2']}

我正在寻找类似的东西 {'k1':['v1','v2']}

Please suggest a solution without using setdefault

请提出一个不使用的解决方案 setdefault

回答by gzc

You can also check key existence before assign.

您还可以在分配之前检查密钥是否存在。

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

回答by Back2Basics

Give collections.defaultdicta try:

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])]

the d = defaultdict(list)line is setting the keys values to be an empty dictionary by default and appending the value to the list in the loop.

d = defaultdict(list)行默认将键值设置为空字典,并将值附加到循环中的列表中。

回答by deepika

The problem with the code is it creates an empty list for 'key' each time the for loop runs. You need just one improvement in the code:

代码的问题是每次 for 循环运行时它都会为“key”创建一个空列表。您只需要对代码进行一项改进:

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

回答by PRASAD

a=[['a',1],['b',2],['c',1],['a',2],['b',3],['a',3]]
d={}
for i in a:
    print (i)
    if i[0] not in d:
       d[i[0]]= [i[1]]
    else:
        d[i[0]].append(i[1])
print (d)



OP : {'a': [1, 2, 3], 'b': [2, 3], 'c': [1]}