我有4个私有变量:
__first = 0
__second = 0
__third = 0
__fourth = 0
我将它们添加到这样的字典中:
numbers = {one: __first, two: __second, three: __third, fourth: __fourth)
当我执行__first += 1
时,字典中的值将保持不变,而原始变量将保持不变。
有帮助吗?
答案 0 :(得分:0)
请检查是否适合您。我只是根据密钥更新了值。您会得到一个刷新字典。您可能会问自己,如果我更新变量,它们将不会在字典中更新?它们将第一次执行,但是第二次将不会执行,因为它们被分配在只能通过索引位置[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}