Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在两个字典中按索引对多个值求和_Python_Dictionary_Sum - Fatal编程技术网

Python 在两个字典中按索引对多个值求和

Python 在两个字典中按索引对多个值求和,python,dictionary,sum,Python,Dictionary,Sum,我有两本字典 first_dict = {2020: [1000, 50], 2021: [2000, 10], 2024: [500, 5]} second_dict = {2019: [500, 20], 2020: [2000, 30], 2021: [1000, 10]} 在第一个值和第二个值具有相同键的情况下,如何求和。制作: resulting_dict = {2019: [500, 20], 2020: [3000, 80], 2021: [3000, 20], 2024: [5

我有两本字典

first_dict = {2020: [1000, 50], 2021: [2000, 10], 2024: [500, 5]}
second_dict = {2019: [500, 20], 2020: [2000, 30], 2021: [1000, 10]}
在第一个值和第二个值具有相同键的情况下,如何求和。制作:

resulting_dict = {2019: [500, 20], 2020: [3000, 80], 2021: [3000, 20], 2024: [500, 5]}

如果确定所有列表的长度均为2,则可以使用以下方法:

first_dict = {2020: [1000, 50], 2021: [2000, 10], 2024: [500, 5]}
second_dict = {2019: [500, 20], 2020: [2000, 30], 2021: [1000, 10]}

keys = set(first_dict).union(second_dict)    
res = {k: list(map(sum, zip(first_dict.get(k, [0, 0]), second_dict.get(k, [0, 0])))) for k in keys}
print(res)  # -> {2019: [500, 20], 2020: [3000, 80], 2021: [3000, 20], 2024: [500, 5]}

如果值列表的长度可能不同,我将使用:

res = {k: list(map(sum, zip_longest(first_dict.get(k, [0]), 
                                    second_dict.get(k, [0]), 
                                    fillvalue=0))) for k in keys}