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,910 points
2,672 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,300 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
• 58,020 points
8,378 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
• 58,020 points
1,119 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, 2020 in Python by Rangertech_hacker234
8,891 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
19,033 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,464 views
0 votes
1 answer
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,300 points
1,669 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,300 points
1,401 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP