📜  Python - 字典值映射求和

📅  最后修改于: 2022-05-13 01:54:30.441000             🧑  作者: Mango

Python - 字典值映射求和

给定一个带有值列表的字典,我们的任务是提取使用映射找到的值的总和。

方法 1:使用循环+ items()

在这种情况下,每个键都在字典中迭代,每个字典的每个值都被迭代。使用初始化的映射和字典进行迭代和求和。

Python3
# Python3 code to demonstrate working of
# Dictionary Values Mapped Summation
# Using loop + items()
  
# initializing dictionary
test_dict = {4 : ['a', 'v', 'b', 'e'],
             1 : ['g', 'f', 'g'],
             3 : ['e', 'v']}
               
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# values mapped 
map_vals = {'a' : 3, 'g' : 8, 'f' : 10,
            'b' : 4, 'e' : 7, 'v' : 2}
  
res = dict()
# items() getting keys and values
for key, vals in test_dict.items():
    sum = 0
    for val in vals:
          
        # summing with mappings
        sum += map_vals[val]
    res[key] = sum
  
# printing result
print("The extracted values sum : " + str(res))


Python3
# Python3 code to demonstrate working of
# Dictionary Values Mapped Summation
# Using dictionary comprehension + sum()
  
# initializing dictionary
test_dict = {4 : ['a', 'v', 'b', 'e'],
             1 : ['g', 'f', 'g'],
             3 : ['e', 'v']}
               
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# values mapped 
map_vals = {'a' : 3, 'g' : 8, 'f' : 10,
            'b' : 4, 'e' : 7, 'v' : 2}
  
# sum() gets sum of each mapped values 
res = {key : sum(map_vals[val] for val in vals) 
       for key, vals in test_dict.items()}
  
# printing result
print("The extracted values sum : " + str(res))


输出:



方法#2:使用字典理解+ sum()

在这里,我们执行使用 sum() 获取每个值的总和的任务。字典理解用于获取键并分配给速记对应的值和。

蟒蛇3

# Python3 code to demonstrate working of
# Dictionary Values Mapped Summation
# Using dictionary comprehension + sum()
  
# initializing dictionary
test_dict = {4 : ['a', 'v', 'b', 'e'],
             1 : ['g', 'f', 'g'],
             3 : ['e', 'v']}
               
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# values mapped 
map_vals = {'a' : 3, 'g' : 8, 'f' : 10,
            'b' : 4, 'e' : 7, 'v' : 2}
  
# sum() gets sum of each mapped values 
res = {key : sum(map_vals[val] for val in vals) 
       for key, vals in test_dict.items()}
  
# printing result
print("The extracted values sum : " + str(res))

输出: