首页 > 解决方案 > Python字典中的变量作为值

问题描述

我有 4 个私有变量:

__first = 0
__second = 0
__third = 0
__fourth = 0

我将它们添加到这样的字典中:

numbers = {one: __first, two: __second, three: __third, fourth: __fourth)

当我这样做__first += 1时,字典中的值不会改变,而原始变量会改变。

有什么帮助吗?

标签: pythonpython-3.x

解决方案


请检查这是否适合您。我只是根据键更新了值。你会得到一个刷新字典。您可能会问自己为什么如果我更新他们不会在字典中更新的变量?他们会第一次这样做,但第二次他们不会,因为它们被分配在只能通过索引位置 [x] 位置访问的其他内存块中。因此,如果您需要更新它,您可能需要在这种情况下根据它们的键更新值。

__first = 0
__second = 0
__third = 0
__fourth = 0

dict = {"first": __first,
        "second": __second,
        "third": __third,
        "fourth": __fourth}


def updateDict(dict, new_key, new_value):

    for key, value in dict.items():
        if key == new_key:
            dict[key] = new_value

    print(dict)

    return dict


dict = updateDict(dict, "first", 1)
# {'first': 1, 'second': 0, 'third': 0, 'fourth': 0}

dict = updateDict(dict, "second", 10)
# {'first': 1, 'second': 10, 'third': 0, 'fourth': 0}

推荐阅读