So say that I have a dictionary with a default value of another dictionary
attributes = { 'first_name': None, 'last_name': None, 'calls': 0 }
accounts = defaultdict(lambda: attributes)
The problem is that the default dictionary that I pass into defaultdict (attributes) is passed as a reference. How can I pass it as a value? So that changing the values in one key doesn't change the values in other keys
For example -
accounts[1]['calls'] = accounts[1]['calls'] + 1
accounts[2]['calls'] = accounts[2]['calls'] + 1
print accounts[1]['calls'] # prints 2
print accounts[2]['calls'] # prints 2
I want each of them to print 1, since I only incremented their respective values for 'calls' once.
Try:
accounts = defaultdict(attributes.copy)
Since Python 3.3 lists
s also have copy
method so you can use it the same way as above with defaultdict
s when you need a dict with a list as a default value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With