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, 2019 in Python by ana1504.k
• 7,890 points
262 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, 2019 by SDeb
• 13,230 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
• 57,530 points
3,076 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
• 57,530 points
125 views
+1 vote
2 answers

python nmap can't find PortScanner attribute

you want install        1.pip uninstall nmap        2.pip install python-nmap in ...READ MORE

answered Jan 25 in Python by Rangertech_hacker234
1,178 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, 2019 in Python by Imran
4,990 views
0 votes
1 answer
+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, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 778 views
0 votes
0 answers
0 votes
1 answer

Can't import tkinter

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

answered May 21, 2019 in Python by SDeb
• 13,230 points
175 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, 2019 in Python by SDeb
• 13,230 points
132 views