-1

Basically, I am trying to extract the values from one dictionary and update the value in another dictionary. I have four lists as follows:

a = [1,1,2,3,4,5]
b = [0,3,0,5,6,0]
c = [2,3,4,5,6,5]
d = [20,30,40,50,60,70]

So I use a defaultdict to store key,value pairs for a,b like:

one = defaultdict(list)
for k, v in zip(a, b):
    one[k].append(v)

two = defaultdict(list)
for k, v in zip(c, d):
  two[k].append(v)

Essentially, b is linked to c so I am trying to extract the values in the two dictionary and then update the values in the one dictionary

So in the end one would look like {1: 30, 3: 50, 4: 60}

This is my code:

three = defaultdict(list)
for k, v in one.items():
  if v in two.keys():
    newvalue = two[v].values()
    three[k].append(newvalue)

But I am now getting an error at line if v in two.keys(): as unhashable type: 'list'. I'm so lost, all I want to do is use the values from one dictionary and then use those values to find the keys (which are the values from the other table) and then get those corressponding values.

  • I'm not getting your expected output: `{1: 30, 3: 50, 4: 60}`. Why is 50 as value to 3? Shouldn't it be 120? – Austin Apr 05 '19 at 11:25

1 Answers1

0

You are creating a dictionary of list in the beginning:

one = defaultdict(list)
for k, v in zip(a, b):
    one[k].append(v)

[output] : defaultdict(list, {1: [0, 3], 2: [0], 3: [5], 4: [6], 5: [0]})

two = defaultdict(list)
for k, v in zip(c, d):
    two[k].append(v)

[output] : defaultdict(list, {2: [20], 3: [30], 4: [40], 5: [50, 70], 6: [60]})

Therefore when calling k,v in one.items(), you are getting a key and a list. Simply switch to iterate through the list , and you should be good to go

three = defaultdict(list)
for k, v in one.items():
    for value in v:
        if value in two.keys():
            newvalue = two[value]
            three[k].append(newvalue)

However I'm getting this output :

defaultdict(list, {1: [[30]], 3: [[50, 70]], 4: [[60]]})

Which sounds reasonable to me, but it is not your expected one, can you please explain ?

Let's try know with dic comprehension

output = { k : two[v_2] for k,v in one.items() for v_2 in v}

[output] : {1: [30], 2: [], 3: [50, 70], 4: [60], 5: []}

Request to sum :

Of course, multiple ways of doing it , the quickest is again with dict_comprehension and sum

output_sum = {k: sum(v) for k,v in output.items()}
Born Tbe Wasted
  • 610
  • 3
  • 13