Bit of a Python newbie but is it possible to do the following?
>>>random_dict=dict(a=2)
>>>addOnlyOneValue(random_dict)
{'a': 3}
>>>addOnlyOneValue(random_dict)
{'a': 3}
What I’ve done:
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)
But if I do this i get following:
>>>random_dict=dict(a=2)
>>>addOnlyOneValue(random_dict)
{'a': 3}
>>>addOnlyOneValue(random_dict)
{'a': 4}
Is it possible to somehow reset random_dict to its original value (here random_dict=dict(a=2)) in the addOnlyOneValue function?
What you want to do is copy() the dictionary:
In your example, you are just making
random_dict2a reference torandom_dict– what you want is to create a new one, with the same values (note that this is a shallow copy, so if your dictionary has mutable items, the new dictionary will point to those items still, which could cause seemingly weird behaviour).Note that rather than looping manually, you could do this with a dictionary comprehension:
Dictionary comprehensions are the best way to create new dictionaries by modifying values from existing data structures.