搜索键并从多个字典中读取



包含不同键和值的几个字典

通过循环键列表,我想返回它们在字典中的值(当键可用时),并对它们求和。

问题是,有些键并不是在所有的字典中都可用。

我需要想出不同的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)

如果没有找到密钥,可以传递0。

for each in ["Mike", "Lilly", "David"]:
print(each, dict_1.get(each, 0)*1 + dict_2.get(each, 0)*2 + dict_3.get(each, 0)*3)

输出:

Mike 30
Lilly 26
David 3

由于字典是用顺序数字命名的,所以更精简的方法是将它们放在一个列表中,并使用enumerate生成因子,当按键求和时,这些因子应用于每个字典中的值:

records = [
{"Mike": 1, "Lilly": 2, "David": 3},
{"Mike": 4, "Peter": 5, "Kate": 6},
{"Mike": 7, "Lilly": 8, "Jack": 9}
]
for name in "Mike", "Lilly", "David":
print(name, sum(factor * record.get(name, 0) for factor, record in enumerate(records, 1)))

这个输出:

Mike 30
Lilly 26
David 3

(考虑到您正在检查不同字典中元素的总出现次数的总和)我确实认为collections.Counter是完成任务的更好方法:https://docs.python.org/3/library/collections.html collections.Counter

例子
from collections import Counter
counter1 = Counter({"Mike": 1, "Lilly": 2, "David": 3}) #counter object from a mapping
counter2 = Counter({"Mike": 4, "Peter": 5, "Kate": 6})
counter3 = Counter({"Mike": 7, "Lilly": 8, "Jack": 9})
countertotal = counter1+counter2+counter2+counter3+counter3+counter3
>>>countertotal
Counter({'Mike': 30,
'Lilly': 26,
'David': 3,
'Peter': 10,
'Kate': 12,
'Jack': 27})

元素出现次数可以直接计算:

for each in ["Mike", "Lilly", "David"]:
print(countertotal[each])
30
26
3

检查元素是否存在不会抛出错误:

for each in ["Ada", "Albert", "Adrian"]:
print(countertotal[each])
0
0
0

您可以在尝试访问key之前检查它是否在字典中。

dict_list = [
{"Mike": 1, "Lilly": 2, "David": 3},
{"Mike": 4, "Peter": 5, "Kate": 6},
{"Mike": 7, "Lilly": 8, "Jack": 9},
]
dict_res = {"Mike": 0, "Lilly": 0, "David": 0}
#loop through each of the names you want
for key in dict_res.items():
x = 1
#loop through each of your dictionaries
for dict in dict_list:
if key in dict:
# multiply by dictionary number and add to result value
dict_res[key] += dict[key] * x
x += 1
print(dict_res)
Output:  {'Mike': 30, 'Lilly': 26, 'David': 3}

相关内容

  • 没有找到相关文章