Rahul Sharma
Rahul Sharma

Reputation: 2495

Create a dictionary by zipping two lists with duplicates

I have two lists with me like the following:

p = ['CRT6423', 'CIN1198C', 'CSS001', 'PP001', 'PS001', 'PL001', 'FIN1151A', 'FSS001', 
'PP001', 'PS001', 'PL001', 'FIN1198A', 'FSS001']

q = [2, 6, 8, 4, 4, 4, 8, 12, 6, 6, 6, 36, 42]

Elements in p are product codes and elements in q are the corresponding quantity.

How can I make a dictionary from these two lists which is something like this:

p_q = {'CRT6423': 2,
 'CIN1198C': 6,
 'CSS001': 8,
 'PP001': 10,   #4+6
 'PS001': 10,   #4+6
 'PL001': 10,   #4+6
 'FIN1151A': 8,
 'FSS001': 54,   #12+42
 'FIN1198A': 36}

Such that wen an entry is repeated it should get adds to the value instead of replacing it

Upvotes: 1

Views: 40

Answers (2)

Rakesh
Rakesh

Reputation: 82765

Using collections.defaultdict

Ex:

from collections import defaultdict

p = ['CRT6423', 'CIN1198C', 'CSS001', 'PP001', 'PS001', 'PL001', 'FIN1151A', 'FSS001', 'PP001', 'PS001', 'PL001', 'FIN1198A', 'FSS001']
q = [2, 6, 8, 4, 4, 4, 8, 12, 6, 6, 6, 36, 42]
result = defaultdict(int)

for k, v in zip(p, q):
    result[k] += v

print(result)   # OR print(dict(result))

Output:

defaultdict(<class 'int'>,
            {'CIN1198C': 6,
             'CRT6423': 2,
             'CSS001': 8,
             'FIN1151A': 8,
             'FIN1198A': 36,
             'FSS001': 54,
             'PL001': 10,
             'PP001': 10,
             'PS001': 10})

Upvotes: 1

Tom Karzes
Tom Karzes

Reputation: 24052

You could do something like this:

p_q = {}
for pv, qv in zip(p, q):
    if pv in p_q:
        p_q[pv] += qv
    else:
        p_q[pv] = qv

Upvotes: 1

Related Questions