Can't pickle defaultdict

0 votes
I have a defaultdict that looks like this:

dict1 = defaultdict(lambda: defaultdict(int))
 

The problem is, I can't pickle it using cPickle. So what is module-level function and How can I use the dictionary with cPickle?
Apr 8 in Python by ana1504.k
• 7,430 points
38 views

1 answer to this question.

0 votes
A module-level function is a function which is defined at module level, that means it is not an instance method of a class, it's not nested within another function, and it is a "real" function with a name, not a lambda function.

So, to pickle your defaultdict, create it with module-level function instead of a lambda function:

def dd():
    return defaultdict(int)

dict1 = defaultdict(dd) # dd is a module-level function
 

then you can pickle it

tmp = pickle.dumps(dict1) # no exception
new = pickle.loads(tmp)
answered Apr 8 by SDeb
• 12,280 points

Related Questions In Python

0 votes
1 answer

Can't Click an Element in Python Selenium After Successfully Finding It

I've encountered this problem of not being ...READ MORE

answered Oct 4, 2018 in Python by Priyaj
• 56,160 points
890 views
0 votes
1 answer

Can't Click an Element in Python Selenium After Successfully Finding It

I've encountered this problem of not being ...READ MORE

answered Oct 8, 2018 in Python by Priyaj
• 56,160 points
76 views
0 votes
1 answer

python nmap can't find PortScanner attribute

As I can see in the error ...READ MORE

answered Jan 30 in Python by Omkar
• 67,120 points
292 views
0 votes
1 answer

Python error saying "AttributeError: can't set attribute"

change your code to the following: @x.setter def x(self, ...READ MORE

answered May 30 in Python by Imran
132 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 128 views
0 votes
1 answer

Can't import tkinter

You can Try this code to import ...READ MORE

answered May 21 in Python by SDeb
• 12,280 points
28 views
0 votes
1 answer

More Pythonic way of counting things in a heavily nested defaultdict

You can try the following, this might ...READ MORE

answered Jun 20 in Python by SDeb
• 12,280 points
9 views