Sorry if this question has been posted before, but I've had trouble finding an answer to this.
When dictionaries are instantiated as follows:
foo = bar = {'a': 0}
or
foo = {'a':0}
bar = foo
Updating one dictionary affects the other:
foo['a'] += 1
print(foo)
// {'a': 1}
print(bar)
// {'a': 1}
Yet when they are instantiated separately:
foo = {'a':0}
bar = {'a':0}
foo['a'] += 1
print(foo)
// {'a':1}
print(bar)
// {'a':0}
However, when variables are instantiated in a similar way:
foo = bar = 0
foo += 1
print(foo)
// 1
print(bar)
// 0
Firstly, what's going on here? Are the variables being set equal to the same dictionary object?
Secondly, how can I copy a dictionary to another variable and update that second variable without affecting the first? For example, I'm trying to append similar dictionaries to a list, but with one key value changed:
dic = {"foo":0,"bar":1}
list1 = [1,2,3,4]
list2 = []
for num in list1:
temp = dic
temp["bar"] = num
list2.append(temp)
print(list2)
// [{"foo":0,"bar":4},{"foo":0,"bar":4},{"foo":0,"bar":4},{"foo":0,"bar":4}]
In this example, it's fairly easy to instead do the following:
list1 = [1,2,3,4]
list2 = []
for num in list1:
list2.append({'foo':0,'bar':num})
print(list2)
// [{"foo":0,"bar":1},{"foo":0,"bar":2},{"foo":0,"bar":3},{"foo":0,"bar":4}]
but for a dictionary with many keys, is there a way to do this without hardcoding a new dictionary?
Thank you!