简体   繁体   English

如何在python 2.7中为给定键添加值?

[英]How to add a value to a given key in python 2.7?

I have a list of keys->values that I want to add to a dictionary. 我有一个key->值列表,我想添加到字典中。 Some of the keys appear more than once with different values, so I have to make a dictionary that will contain more than one value per key. 有些键会出现不同的值,因此我必须创建一个每个键包含多个值的字典。 Couldn't find a way to do it. 找不到办法做到这一点。

You can use setdefault function in dict 您可以在dict使用setdefault函数

myDict, items = dict(), [[1, 2], [1, 3], [2, 4]]
for key, value in items:
    myDict.setdefault(key, []).append(value)
print myDict

Output 产量

{1: [2, 3], 2: [4]}

or you can use collections.defaultdict 或者您可以使用collections.defaultdict

from collections import defaultdict
myDict, items = defaultdict(list), [[1, 2], [1, 3], [2, 4]]
for key, value in items:
    myDict[key].append(value)
print myDict

Output 产量

defaultdict(<type 'list'>, {1: [2, 3], 2: [4]})

You don't indicate if you have the same value multiple times for the same key. 对于同一个键,您不会多次指示您具有相同的值。 In any case you want to use a set() if you want to associate multiple values with one value to prevent duplicates: 在任何情况下,如果要将多个值与一个值相关联以防止重复,则要使用set()

org_list = [(1,2), (1,3), (2,1), (2,2), (1,3)]
result = {}
for k, v in org_list:
    result.setdeault(k, set()).add(v)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM