【问题标题】:increment value in dictionary based on key in another dictionary根据另一个字典中的键增加字典中的值
【发布时间】:2018-11-15 03:00:44
【问题描述】:

我有一个 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}

【问题讨论】:

    标签: python dictionary python-2.x


    【解决方案1】:
    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)
    

    【讨论】:

    • 亲爱的主,我希望事情不会那么容易,不过还是谢谢你!
    猜你喜欢
    • 2017-11-06
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 2019-06-19
    相关资源
    最近更新 更多