2016-11-24 66 views
1

我试图从一组唯一值的建立一个字典作为键和元组提供的项目的压缩列表。Python。添加多个项目键在字典

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

你不需要任何的。只需使用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) 
+0

感谢。像魅力一样工作。不知道那个模块。 – ShaunO

0

dict S,所有按键都是独一无二的,每个键只能有一个值。

解决这个最简单的方法是有字典的值是list,如仿效所谓的多重映射。在列表中,您拥有所有被键映射到的元素。

编辑:

你可能想看看这个安装包的PyPI:https://pypi.python.org/pypi/multidict

引擎盖下,但是,它可能是因为上述作品。

据我所知,没有什么内置支持你所追求的。

1

你可以做到这一点使用dict.setdefault方法:

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

或者,使用collections.defaultdict由TigerhawkT3提及。


问题与您的代码:你是不是做了检查现有key。每次你做SrvCodeDct[r] = item,你与item值更新r关键的前值。为了解决这个问题,必须添加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提及)简化,或使用dict.setdefault方法为:

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

@ Moinududdin我也喜欢这个答案,尤其是因为你不需要导入集合,但由于两者都很好,我已经选择了TigerhawkT3,所以我会坚持。非常感谢。 – ShaunO

相关问题