Search code examples
pythondictionaryhashpass-by-referencedefaultdict

Python - how to pass a dictionary into defaultdict as value and not as a reference


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.


Solution

  • Try:

    accounts = defaultdict(attributes.copy)
    

    Since Python 3.3 listss also have copy method so you can use it the same way as above with defaultdicts when you need a dict with a list as a default value.