ShaunO ShaunO - 16 days ago 6
Python Question

Python. Adding multiple items to keys in a dict

I am trying to build a dict from a set of unique values to serve as the keys and a zipped list of tuples to provide the items.

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}


But I am getting:

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


here is my code so far:

#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

Answer

You don't need any of that. Just use a 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)