蟒蛇。将多个项添加到词典中的键

时间:2016-11-24 21:22:24

标签: python dictionary

我正在尝试从一组唯一值构建一个dict作为键和一个用于提供项目的压缩元组列表。

set = ("a","b","c")

lst 1 =("a","a","b","b","c","d","d")
lst 2 =(1,2,3,3,4,5,6,)

zip = [("a",1),("a",2),("b",3),("b",3),("c",4),("d",5)("d",6)

dct = {"a":1,2 "b":3,3 "c":4 "d":5,6}

但我得到了:

dct = {"a":1,"b":3,"c":4,"d":5}

到目前为止,这是我的代码:

#make two lists 

rtList = ["EVT","EVT","EVT","EVT","EVT","EVT","EVT","HIL"]
raList = ["C64G","C64R","C64O","C32G","C96G","C96R","C96O","RA96O"]

# make a set of unique codes in the first list

routes = set()
for r in rtList:
    routes.add(r)

#zip the lists

RtRaList = zip(rtList,raList)
#print RtRaList

# make a dictionary with list one as the keys and list two as the values

SrvCodeDct = {}

for key, item in RtRaList:
    for r in routes:
        if r == key:
            SrvCodeDct[r] = item

for key, item in SrvCodeDct.items():
    print key, item

3 个答案:

答案 0 :(得分:5)

你不需要任何这些。只需使用collections.defaultdict

import collections

rtList = ["EVT","EVT","EVT","EVT","EVT","EVT","EVT","HIL"]
raList = ["C64G","C64R","C64O","C32G","C96G","C96R","C96O","RA96O"]

d = collections.defaultdict(list)

for k,v in zip(rtList, raList):
    d[k].append(v)

答案 1 :(得分:1)

您可以使用documentation方法实现此目的:

my_dict = {}
for i, j in zip(l1, l2):
    my_dict.setdefault(i, []).append(j)

将返回my_dict的值为:

>>> my_dict
{'a': [1, 2], 'c': [4], 'b': [3, 3], 'd': [5, 6]}

或者,使用TigerhawkT3提到的dict.setdefault

您的代码问题:您没有检查现有的key。每次执行SrvCodeDct[r] = item时,您都会使用r值更新item密钥的先前值。要解决此问题,您必须将if条件添加为:

l1 = ("a","a","b","b","c","d","d")
l2 = (1,2,3,3,4,5,6,)

my_dict = {}
for i, j in zip(l1, l2):
    if i in my_dict:          # your `if` check 
        my_dict[i].append(j)  # append value to existing list
    else:
        my_dict[i] = [j]  


>>> my_dict
{'a': [1, 2], 'c': [4], 'b': [3, 3], 'd': [5, 6]}

但是,可以使用collections.defaultdict(如TigerhawkT3所述)或使用collections.defaultdict方法简化此代码:

my_dict = {}
for i, j in zip(l1, l2):
    my_dict.setdefault(i, []).append(j)

答案 2 :(得分:0)

dict中,所有密钥都是唯一的,每个密钥只能有一个值。

解决此问题的最简单方法是将字典的值设为list,以模拟所谓的多图。在列表中,您拥有按键映射到的所有元素。

编辑:

您可能想查看此PyPI包:https://pypi.python.org/pypi/multidict

然而,在引擎盖下,它可能如上所述起作用。

Afaik,没有任何内置支持你所追求的目标。