根据另一个字典中的键在字典中增加值

时间:2018-11-15 03:00:44

标签: python dictionary python-2.x

我有一本masterDict字典,其键为“ 1”至“ 8”,其值设置为0

{'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0}

我还使用anotherDict来查找包含最接近另一个值的键(我使用不同的值多次执行此操作)。

其中一个其他值的示例为value1 = 900

anotherDict的示例为:

{'1': 74, '2': 938, '3': 28, '4': 10, '5': 100, '6': 33, '7': 45, '8': 99}

我用来在value1中找到最接近anotherDict的值的代码是:

closestValue1 = key, value = min(anotherDict.items(), key=lambda (_, v): abs(v - value1))

在这种情况下,closestValue1返回:

{'2': 938}

如何处理并将2中的密钥masterDict值增加1?

因此,masterDict将包含:

{'1': 0, '2': 1, '3': 0, '4': 0, '5': 0, '6':0, '7':0, '8': 0}

1 个答案:

答案 0 :(得分:2)

master_dict = {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0}
another_dict = {'1': 74, '2': 938, '3': 28, '4': 10, '5': 100, '6': 33, '7': 45, '8': 99}
target_val = 900
target_key, _ = min(another_dict.items(), key=lambda x: abs(target_value-x[1])) 
master_dict[target_key]+=1
print (master_dict)