简体   繁体   中英

How to sum values when zipping similar key to build a dict

I have A = [a, b, c, d, a, d, c] and B=[1, 2, 3, 4, 5, 6, 7]

Why dict(zip(A,B)) doesn't return {'a': 6, 'b': 2, 'c': 10, 'd': 10} ?

How to make it works?

Using a simple iteration

Ex:

A = ["a", "b", "c", "d", "a", "d", "c"] 
B= [1, 2, 3, 4, 5, 6, 7]

result = {}
for a, b in zip(A, B):
    if a not in result:
        result[a] = 0
    result[a] += b
print(result)

Or using collections.defaultdict

Ex:

from collections import defaultdict
result = defaultdict(int)
for a, b in zip(A, B):
    result[a] += b
pprint(result)

Output:

{'a': 6, 'b': 2, 'c': 10, 'd': 10}

dict will just over-write the values.. what you want won't come so easily. You'd need something like this:

#!/usr/bin/env python3
from collections import defaultdict

A = ["a", "b", "c", "d", "a", "d", "c"]
B = [1, 2, 3, 4, 5, 6, 7]

output = defaultdict(int)

for a,b in zip(A,B):
        output[a] += b

print(output)

The result:

defaultdict(<class 'int'>, {'a': 6, 'b': 2, 'c': 10, 'd': 10})

defaultdict will set each new keys value to 0 by default.. allowing us to call += on each key without error.. giving us the sum we need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM