How to create a new defaultdict (list) in place based on an existing dictionary of the same type and use the original name

I have two dictionaries, there are several matches in the keys (and values) after they are created. I want to remove the key from one of them, the values โ€‹โ€‹that exist in the other. Based on this question and Alex Martelli's answer, I tried

from collections import defaultdict some_dictionary # a defaultdict(list) other_dictionary # a defaultdict(list) has some duplicate k,v pairs other_dictionary = defaultdict((key,other_dictionary[key]) for key in other_dictionary if key not in some_dictionary) 

When I do this, I get an error

 TypeError: first argument must be callable 
+4
source share
2 answers

Try the following:

 other_dictionary = defaultdict(list, ((k, v) for k, v in other_dictionary.iteritems() if k not in some_dictionary)) 

Note that defaultdict must accept as the first argument to determine the default value. There was no list argument in your code.

Other than that, your algorithm was essentially correct, but it can be written more concisely using iteritems() , as shown above.

+4
source

Use iteritems

 other_dictionary = defaultdict(list, ((key,values) for key, values in other_dictionary.iteritems() if key not in some_dictionary)) 
0
source

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


All Articles