Python - how to pass a dictionary to defaultdict as a value, not as a link

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 to defaultdict (attributes) is passed as a link. How to convey it as a value? Thus, changing values ​​in one key does not change values ​​in other keys

For instance -

 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 only once increased their corresponding values ​​for the "calls".

+5
source share
2 answers

Try:

 accounts = defaultdict(attributes.copy) 

Since Python 3.3 lists also has a copy method , so you can use it the same way as described above with defaultdict when you need a dict file with a list as the default value.

+8
source

I really like the warvariuc solution. However, remember that you are not passing the dict to defaultdict ..., which will result in a TypeError , because this argument must be callable. You could just use a literal in lambda. Or better yet, define a helper function:

 >>> def attribute(): ... return { 'first_name': None, 'last_name': None, 'calls': 0 } ... >>> accounts = defaultdict(attribute) >>> accounts[1]['calls'] = accounts[1]['calls'] + 1 >>> accounts[2]['calls'] = accounts[2]['calls'] + 1 >>> print(accounts[1]['calls']) 1 >>> print(accounts[2]['calls']) 1 
+2
source

Source: https://habr.com/ru/post/1263933/


All Articles