Kallol
Kallol

Reputation: 2189

create dictionary from two list with the addition of values with same key

I have two lists like below,

l1=['a', 'b', 'c', 'c', 'a','a','d','b']
l2=[2, 4, 6, 8, 10, 12, 14, 16]

Now want to create a dictionary from above list such as- key would be unique from l1 and the values from l2 will be added,

so final dictionary would look like,

d={'a':24, 'b':20, 'c': 14, 'd':14}

I could do this using a for loop but execution time will be more, looking for some python shortcuts to do this most efficiently.

Upvotes: 0

Views: 212

Answers (4)

Sebastien D
Sebastien D

Reputation: 4482

With a dict of comprehension:

from  more_itertools import unique_everseen
d = {i: sum([l2[x] for x in [y for y,val in enumerate(l1) if val==i]]) for i in  list(unique_everseen(l1))}

Output:

{'a':24, 'b':20, 'c': 14, 'd':14}

Upvotes: 1

ran632
ran632

Reputation: 1199

l1 = ['a', 'b', 'c', 'c', 'a','a','d','b']
l2 = [2, 4, 6, 8, 10, 12, 14, 16]    

idx = 0
d = {}
for v in l1:
  d[v] = d.get(v, 0) + l2[idx]
  idx += 1

print d
# {'a': 24, 'b': 20, 'c': 14, 'd': 14}

Upvotes: 0

Austin
Austin

Reputation: 26039

You can use collections.defaultdict for this with zip to iterate parallely:

from collections import defaultdict

l1 = ['a', 'b', 'c', 'c', 'a','a','d','b']
l2 = [2, 4, 6, 8, 10, 12, 14, 16]

d = defaultdict(int)
for k, v in zip(l1, l2):
    d[k] += v

print(d)
# {'a': 24, 'b': 20, 'c': 14, 'd': 14}

Upvotes: 2

Aleksander Ikleiw
Aleksander Ikleiw

Reputation: 2685

You have to use the zip() function. In it we iterate in the 2 lists, then we are creating a new dictionary key j which comes from the l1 and assigning a value to it i which comes from the l2. If the key from the l1 is in the dictionary key already, it value will be added as you wanted to.

l1=['a', 'b', 'c', 'c', 'a','a','d','b']
l2=[2, 4, 6, 8, 10, 12, 14, 16]
output = {}
for j, i in zip(l1, l2):
    if j in output.keys():
        output[j] = output[j] + i
    else:
        output[j] = i
print(output)

Upvotes: 0

Related Questions