简体   繁体   中英

Adding values of one dictionary if the keys match the keys of the other dictionary

I am new to python. I'd like to ask for your assistance regarding operations with dictionaries. I guess, the question is a bit basic. But, I'm kinda stuck. I need to get the total of values in dict2 corresponding the "JJ" values in dict1. Since "JJ" in dict1 is associated with keys "A" and "B", the corresponding values in dict2 are 30 and 100, which sums to 130 Thank you! Rn

My code (I'm getting the sum of all values in dict2=145 after step 2 instead of just A+B=130)

dict1 = {"A":"JJ", "B":"JJ", "C":"X"}
dict2 = {"A":30, "B":100, "C":15}
dict3=dict()
for (kk, vv) in dict1.items():
    ref_val="JJ"
    if vv == ref_val:
        dict3[kk] = vv
print(dict3)

total_points=0
for (kk, vv) in dict2.items(): 
    for (kk, vv) in dict3.items(): 
        total_points = sum(vv for vv in dict2.values())
print(total_points)

I hope I understood the question correctly. I so, this should work:

dict1 = {"A": "JJ", "B": "JJ", "C": "X"}
dict2 = {"A": 30, "B": 100, "C": 15}

keys = set(k for k, v in dict1.items() if v == "JJ")
total_points = sum(dict2.get(k, 0) for k in keys)

print(total_points)
  1. keys : using list comprehension the keys having value equal to JJ are selected
  2. total_points : the values corresponding to those keys are fetch from dict2 and summed on the fly. If a key from keys is not present in dict2 (which is not the case, btw) 0 (zero) is fetched instead (so it won't affect the sum)

I like the other answer but I would probably solve this problem a little more generically:

from collections import defaultdict

dict1 = {"A": "JJ", "B": "JJ", "C": "X"}
dict2 = {"A": 30, "B": 100, "C": 15}

val_to_keys = defaultdict(list)

for key, val in dict1.items():
    val_to_keys[val].append(dict2.get(key, 0))

# Note that now val_to_keys contains:
# {'JJ': [30, 100], 'X': [15]}

if 'JJ' in val_to_keys:
    print(sum(val_to_keys['JJ'])) # 130
# or you can one line the print
print(sum(val_to_keys.get('JJ', []))) # 130

This way you can only need to iterate over the dict1 once and you can pull out any value you want.

Note that if all you care about is the sums then it can be even more efficient by calculating the sum during the initial iteration. (I use a normal dict instead of a defaultdict here just to show how you can do it both with regular dictionaries and defaultdicts).

dict1 = {"A": "JJ", "B": "JJ", "C": "X"}
dict2 = {"A": 30, "B": 100, "C": 15}

val_to_keys = {}

for key, val in dict1.items():
    val_to_keys[val] = val_to_keys.get(val, 0) + dict2.get(key, 0)

# Note that now val_to_keys contains:
# {'JJ': 130, 'X': 15}

if 'JJ' in val_to_keys:
    print(val_to_keys['JJ']) # 130

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