shobhit
shobhit

Reputation: 700

Python: Merging Two Lists

I have two lists

    list1= [6, 1, 8, 1, 2]
   list2= ["Mail Opened", "Mail Not Opened", "Mail Opened", "Mail Not Opened", "Mail Not Opened"]

I was to trying results like

(14,"mailopened") (4,"mailnotopened")

First i tried to convert them Dict but it does not accept duplicate values. is it Possible to add these lists according to the second list.

Upvotes: 2

Views: 417

Answers (3)

Steve Tjoa
Steve Tjoa

Reputation: 61124

dict_out = dict()
for list1_val, k in zip(list1, list2):
    dict_out[k] = dict_out.get(k, 0) + list1_val

Output:

In [10]: dict_out
Out[10]: {'not open': 4, 'open': 14}

Explanation:

  1. zip(list1, list2) is equivalent to the sequence (6, 'open'), (1, 'not open'), ..., (2, 'not open').

  2. For dictionary dict_out, dict_out.get(k, 0) returns dict_out[k] if it exists, otherwise 0.

  3. Therefore, the for loop iterates over the five (value, key) pairs and accumulates them in the dictionary dict_out.

Upvotes: 4

voithos
voithos

Reputation: 70632

Use a defaultdict and simply add the values from list1.

from collections import defaultdict

list1 = [6, 1, 8, 1, 2]
list2 = ["Mail Opened", "Mail Not Opened", "Mail Opened", "Mail Not Opened", "Mail Not Opened"]

added = defaultdict(int)

for i, k in enumerate(list2):
    added[k] += list1[i]

This works because defaultdict supplies a default value if a key is accessed which doesn't exist. In this case, it will supply a default of 0 because we specified that it is an int type.

Use of enumerate() stolen from @GaretJax. :)

Upvotes: 7

GaretJax
GaretJax

Reputation: 7780

from collections import defaultdict

list1 = [6, 1, 8, 1, 2]
list2 = ["Mail Opened", "Mail Not Opened", "Mail Opened", "Mail Not Opened", "Mail Not Opened"]

d = defaultdict(lambda:0)

for i, k in enumerate(list2):
    d[k]+=list1[i]

print d
print d.items()

Edit: voitos was faster with an identical solution (see above)

Upvotes: 2

Related Questions