Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 663
geoJshaun Avatar asked Nov 24 '16 21:11

geoJshaun


2 Answers

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)
like image 87
TigerhawkT3 Avatar answered Oct 05 '22 23:10

TigerhawkT3


You may achieve this using dict.setdefault method as:

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

which will return value of my_dict as:

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

OR, use collections.defaultdict as mentioned by TigerhawkT3.


Issue with your code: You are not making the check for existing key. Everytime you do SrvCodeDct[r] = item, you are updating the previous value of r key with item value. In order to fix this, you have to add if condition as:

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

However this code can be simplified using collections.defaultdict (as mentioned by TigerhawkT3), OR using dict.setdefault method as:

my_dict = {}
for i, j in zip(l1, l2):
    my_dict.setdefault(i, []).append(j)
like image 36
Moinuddin Quadri Avatar answered Oct 06 '22 01:10

Moinuddin Quadri