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

标签 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}

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

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

在本例中,closestValue1 返回:

{'2': 938}

如何获取该值并将 masterDict 中的键 2 值增加 1?

因此,masterDict 将包含:

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

最佳答案

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)

关于python - 根据另一个字典中的键增加字典中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53311794/

相关文章:

python - Pandas Dataframe 检查交集并填写新的 dataframe

python - 为什么我得到 None 值,并且为什么该数字仍在 Python 中打印?

python - 如何在 Django 中获取阿拉伯字符串的 Unicode 表示?

python - 如何安装与不同版本的Python关联的pip

python - 为什么我的 elif 语句不会执行,而我的 if 语句会在 Python 中执行?

python - 被定义类型的类常量

python - 无法从字符串中删除 "\r\n"

python - Python 中的随机性

python - 计算图中节点距离时的关键错误

python - Django 迭代列表中的字典并在模板中显示数据