Reputation: 185
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?
Upvotes: 2
Views: 81
Reputation: 2097
Assignment of a dictionary (or any other object except string or a number) to another variable results of assignment of a reference to that object, it does not create a copy. You might do:
random_dict2 = dict(random_dict)
Similar for lists:
my_copy = list(some_list)
Note that this copy is "shallow", that means that only list is copied and will contain references to the contained objects, not copies of the objects. Read more about copying in python.
Upvotes: 1
Reputation: 89087
What you want to do is copy() the dictionary:
random_dict2 = random_dict.copy()
In your example, you are just making random_dict2
a reference to random_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:
def addOnlyOneValue(random_dict):
print({key: value+1 for key, value in random_dict.items()})
Dictionary comprehensions are the best way to create new dictionaries by modifying values from existing data structures.
Upvotes: 3