简体   繁体   中英

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. 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

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

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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