Python 新手,但是可以执行以下操作吗?
>>>random_dict=dict(a=2)
>>>addOnlyOneValue(random_dict)
{'a': 3}
>>>addOnlyOneValue(random_dict)
{'a': 3}
我做了什么:
def addOnlyOneValue(random_dict):
random_dict2=random_dict #I thought random_dict and random_dict2 would be modified independently
for val in random_dict2.keys():
random_dict2[val]+=1
print (random_dict2)
但是如果我这样做,我会得到以下结果:
>>>random_dict=dict(a=2)
>>>addOnlyOneValue(random_dict)
{'a': 3}
>>>addOnlyOneValue(random_dict)
{'a': 4}
是否可以在 addOnlyOneValue 函数中以某种方式将 random_dict 重置为其原始值(此处 random_dict=dict(a=2))?
最佳答案
你想做的是copy()字典:
random_dict2 = random_dict.copy()
在您的示例中,您只是将 random_dict2
设为对 random_dict
的引用 - 您想要的是创建一个具有相同值的新引用(请注意,这是浅拷贝,因此如果您的字典有可变项目,新字典仍将指向这些项目,这可能会导致看似奇怪的行为)。
请注意,您可以使用 dictionary comprehension 来执行此操作,而不是手动循环。 :
def addOnlyOneValue(random_dict):
print({key: value+1 for key, value in random_dict.items()})
字典推导式是通过修改现有数据结构中的值来创建新字典的最佳方式。
关于python - 在 Python 中保持字典中的值相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13570757/