简体   繁体   English

将多个值添加到字典键

[英]Add multiple values to a dictionary key

I have two lists: 我有两个清单:

list1 = ['670', '619', '524', '670', '693', '693', '693', '632', '671']
list2 = ['JAIPUR', 'MUMBAI', 'DELHI', 'UDAIPUR', 'GOA', 'GOA', 'GOA', 'LUCKNOW', 'JAIPUR']

I want to make a dictionary out of this. 我想以此做一本字典。 Please note the two lists exactly in the order that it should be mapped into. 请注意两个列表完全按照应映射到的顺序排列。 Like for key '670' value us 'JAIPUR' and so on. 就像键“ 670”一样,我们值“ JAIPUR”,依此类推。

But when I tried, it gives output as: 但是当我尝试时,它的输出为:

d = dict(zip(list1, list2))

{'670': 'UDAIPUR', '619': 'MUMBAI', '524': 'DELHI', '693': 'GOA', '632': 'LUCKNOW', '671': 'JAIPUR'}

It takes only the latest value if multiple values are found for a single key. 如果为单个键找到多个值,则仅采用最新值。 However what I want is multiple values for a single key like 670 should have: 但是我想要的是像670这样的单个键的多个值应具有:

'670': ['JAIPUR', 'UDAIPUR']

Can anyone help. 谁能帮忙。

Use defaultdict : 使用defaultdict

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for i,key in enumerate(list1): 
        if list2[i] not in d[key]:            #to add only unique values (ex: '693':'goa')
            d[key].append(list2[i]) 

>>> d
=> defaultdict(<class 'list'>, {'670': ['JAIPUR', 'UDAIPUR'], '619': ['MUMBAI'], 
               '524': ['DELHI'], '693': ['GOA'], '632': ['LUCKNOW'], '671': ['JAIPUR']})

What you need is grouping by the list1 items. 您需要的是按list1项分组。 Use collections.defaultdict object: 使用collections.defaultdict对象:

import collections

list1 = ['670', '619', '524', '670', '693', '693', '693', '632', '671']
list2 = ['JAIPUR', 'MUMBAI', 'DELHI', 'UDAIPUR', 'GOA', 'GOA', 'GOA', 'LUCKNOW', 'JAIPUR']
result = collections.defaultdict(list)

for t in zip(list1, list2):
    result[t[0]].append(t[1])

print(dict(result))

The output: 输出:

{'524': ['DELHI'], '671': ['JAIPUR'], '632': ['LUCKNOW'], '670': ['JAIPUR', 'UDAIPUR'], '619': ['MUMBAI'], '693': ['GOA', 'GOA', 'GOA']}

Since dicts can not have more than one element with the same key the newer values for that key that are assigned to a dict overwrite the older ones. 由于字典使用相同的键最多只能有一个元素,因此分配给字典的键的新值会覆盖较旧的值。

So with this code it works: 因此,使用此代码即可:

list1 = ['670', '619', '524', '670', '693', '693', '693', '632', '671']
list2 = ['JAIPUR', 'MUMBAI', 'DELHI', 'UDAIPUR', 'GOA', 'GOA', 'GOA', 'LUCKNOW', 'JAIPUR']

def extendDictValue(d, key, value):
    if key in d:
        d[key].append(value)
    else:
        d[key] = [value]

d={}
for key, value in zip(list1, list2):
    extendDictValue(d, key, value)

print(d)

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

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