简体   繁体   English

在Python字典中将变量作为值

[英]Variables as Values in Python Dictionary

I have 4 private variables: 我有4个私有变量:

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

I added them to a dictionary like this: 我将它们添加到这样的字典中:

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

When I do __first += 1 , the value in the dictionary won't get changed while the original variable would. 当我执行__first += 1 ,字典中的值不会更改,而原始变量会更改。

Any help? 有什么帮助吗?

Please check if this works for you. 请检查是否适合您。 I Simply Updated the value based on the key. 我只是根据密钥更新了值。 and you get a refresh dictionary. 您会得到一个刷新字典。 You may be asking youself why If I update the variable they wont update in the dictionary? 您可能会问自己,如果我更新变量,它们将不会在字典中更新? they will do the first time, but the second time they wont since they are allocated in other block of memory that can only be accesed via index location [x] position. 它们将第一次执行,但是第二次不会执行,因为它们被分配在只能通过索引位置[x]位置访问的其他内存块中。 So if you need to update it you may need to update the values based on their key in this case. 因此,在这种情况下,如果需要更新它,则可能需要根据它们的键来更新值。

__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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM