我似乎无法在python中解决这个问题,如果有人可以帮助我,我会很高兴。 我基本上有两本词典。
dict_a = { "poop" : 2, "eggs": 3, "pee": 3, "debt": 4 }
dict_b = { "poop" : 10, "pee": 9}
for word, number in dict_a.items():
if word in dict_b.keys():
points = dict_a[word] * dict_b[key]
prints(points)
我的问题是,它似乎并没有起作用。当我比较我的两个词典时,即使它们具有相同的键,它们也不匹配。 是否有更简单的方法来查看两个词典是否具有相同的键,然后将键的值相互相乘?
我想要结果 分数= 47 因为大便的价值为2 * 10,小便的价值为3 * 9.
非常感谢您提前:))
答案 0 :(得分:0)
试试这个。
def mult_dicts(dict1, dict2):
result_dict = {}
for word in dict1:
result_dict[word] = dict1[word]
if word in dict_b:
result_dict[word] *= dict2[key]
else:
result_dict[word] = dict2[key]
return result_dict
或者,如果您只希望它包含两个字典中的键时的条目:
def mult_dicts(dict1, dict2):
result_dict = {}
for word in dict1:
if word in dict_b:
result_dict[word] = dict1[word] * dict2[key]
return result_dict
答案 1 :(得分:0)
你去:
>>> for x in set(dict_a.keys() + dict_b.keys()):
... print(x,dict_b.get(x,1)*dict_b.get(x,1))
...
('pee', 27)
('poop', 20)
('debt', 4)
('eggs', 3)
如果你想要一本字典:
>>> { x:dict_a.get(x,1)*dict_b.get(x,1) for x in set(dict_a.keys() + dict_b.keys())}
{'pee': 27, 'poop': 20, 'debt': 4, 'eggs': 3}
如果你想要列表:
>>> [ [x,dict_a.get(x,1)*dict_b.get(x,1)] for x in set(dict_a.keys() + dict_b.keys())]
[['pee', 27], ['poop', 20], ['debt', 4], ['eggs', 3]]
总分:
>>> sum([ dict_a.get(x,1)*dict_b.get(x,1) for x in set(dict_a.keys()) & set(dict_b.keys())])
47
删除sum以查看值:
>>> [ dict_a.get(x,1)*dict_b.get(x,1) for x in set(dict_a.keys()) & set(dict_b.keys())]
[27, 20]
答案 2 :(得分:0)
当然,这是假设非现值的基数为1。
dict_a = { "poop" : 2, "eggs": 3, "pee": 3, "debt": 4 }
dict_b = { "poop" : 10, "pee": 9}
result = {}
for key in set(dict_a).union(dict_b):
result[key] = dict_a.get(key, 1) * dict_b.get(key, 1)
您也可以使用defaultdict
来阻止明确get(x, 1)
,但此时主要是偏好问题。
答案 3 :(得分:0)
dict_a = { "poop" : 2, "eggs": 3, "pee": 3, "debt": 4 }
dict_b = { "poop" : 10, "pee": 9}
x=raw_input("Word: ")
if x in dict_a:
point=dict_a[x]*dict_b[x]
print point
结果:单词:poop
20
编辑然后:
dict_a = { "poop" : 2, "eggs": 3, "pee": 3, "debt": 4 }
dict_b = { "poop" : 10, "pee": 9}
for x in dict_a:
for y in dict_b:
point=dict_a[x]*dict_b[y]
print point
结果: 27 三十 18 20 36 40 27 30