包含不同键和值的几个字典。通过循环键列表,我希望返回字典中键的值(当键可用时),并对它们求和。问题是,有些键并不是在所有字典中都可用。我需要想出不同的IF语句,看起来很笨拙。尤其是当有更多的字典进来时,变得非常困难。有什么不同的聪明方法可以做到这一点? dict_1 = {"Mike": 1, "Lilly": 2, "David": 3}
dict_2 = {"Mike": 4, "Peter": 5, "Kate": 6}
dict_3 = {"Mike": 7, "Lilly": 8, "Jack": 9}
for each in ["Mike", "Lilly", "David"]:
if each in list(dict_1.keys()) and each in list(dict_2.keys()) and each in list(dict_3.keys()):
print (each, dict_1[each] * 1 + dict_2[each] * 2 + dict_3[each] * 3)
if each in list(dict_1.keys()) and each in list(dict_2.keys()):
print (each, dict_1[each] * 1 + dict_2[each] * 2)
if each in list(dict_2.keys()) and each in list(dict_3.keys()):
print (dict_2[each] * 2 + dict_3[each] * 3)
if each in list(dict_1.keys()) and each in list(dict_3.keys()):
print (each, dict_1[each] * 1 + dict_3[each] * 3)
|