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

geo*_*aun 5 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}
Run Code Online (Sandbox Code Playgroud)

但我得到:

dct = {"a":1,"b":3,"c":4,"d":5}
Run Code Online (Sandbox Code Playgroud)

这是我目前的代码:

#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
Run Code Online (Sandbox Code Playgroud)

Tig*_*kT3 7

你不需要任何这些.只需使用一个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)
Run Code Online (Sandbox Code Playgroud)