2016-11-24 30 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

相關問題