简体   繁体   English

如果键与另一字典的键匹配,则添加一个字典的值

[英]Adding values of one dictionary if the keys match the keys of the other dictionary

I am new to python.我是 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.我需要得到 dict2 中与 dict1 中的“JJ”值相对应的值的总和。 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!由于dict1中的“JJ”与键“A”和“B”相关联,所以dict2中对应的值为30和100,总和为130 谢谢! Rn Rn

My code (I'm getting the sum of all values in dict2=145 after step 2 instead of just A+B=130)我的代码(我在第 2 步之后得到 dict2=145 中所有值的总和,而不仅仅是 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 keys : 使用列表推导选择值等于JJ的键
  2. total_points : the values corresponding to those keys are fetch from dict2 and summed on the fly. total_points :与这些键对应的值是从dict2获取并即时求和的。 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)如果dict2中不存在键中的keys (不是这种情况,顺便说一句),则取 0(零)代替(因此它不会影响总和)

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.这样,您只需遍历dict1一次,就可以提取任何您想要的值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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