ShaunO ShaunO - 5 days ago 6
Python Question

Create a dict from two existing dicts

I have two dicts that have sets as their values.

Dct1 = {'a':[1, 2, 3], 'b':[4, 5, 6, 7], 'c':[8, 9, 10], 'd':[11, 12, 13, 14]}
Dct2 = {'TypeZ':['a', 'b'], 'TypeX':['c', 'd']}


I would like to create another dict that:
1. iterates through the items of the values in Dct1
2. checks if the key of the item's value is an item in the values of Dct2
3. uses the key of dct2 as the key for the new dct and the corresponding items of the values in dict one as the set values for the new dict

Dct3 = {'TypeZ':[1, 2, 3, 4, 5, 6, 7], 'TypeX':[8, 9, 10, 11, 12, 13, 14]}


I also want to avoid having duplicates in the values of Dct3.

Here's the snippet of the code I'm currently struggling with (the other dicts have already been successfully built):

RateByType = {}

for key, item in RoRaDct.items():
for i, j in TpRtDct.items():
for x in item:
for y in j:
if key == y:
RateByType[i].add(item)


But it is producing a key error. I've tried using defaultdict(set) but get a TypeError: unhashable type: set. The latter is the method I used to build the first two dicts.

Answer

Make a set out of Dct2's keys and then create a defaultdict for Dct3, looping over Dct2's keys and their corresponding values:

import collections
Dct1 = {'a':[1,2,3],'b':[4,5,6,7],'c':[8,9,10],'d':[12,12,13,14]}
Dct2 = {'TypeZ':['a','b'],'TypeX':['c','d']}
s = set(Dct2)
d = collections.defaultdict(list)
for key in Dct2:
    for k in Dct2[key]:
        d[key].extend(Dct1[k])

Result:

>>> import pprint
>>> pprint.pprint(d)
{'TypeX': [8, 9, 10, 12, 12, 13, 14],
 'TypeZ': [1, 2, 3, 4, 5, 6, 7]}
Comments