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
• 6,150 points
28 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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
• 9,740 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,120 points
617 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,120 points
66 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
• 66,050 points
180 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
27 views
0 votes
1 answer

Can't import tkinter

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

answered 5 days ago in Python by SDeb
• 9,740 points
9 views
0 votes
1 answer

Can't find an element Using Selenium

The reason you can't locate the item ...READ MORE

answered Mar 26, 2018 in Selenium by nsv999
• 5,030 points
183 views
+6 votes
5 answers

can't remove SSIS variables using remove method on PowerShell

you're missing the additional $environment.Alter() after your ...READ MORE

answered Mar 27, 2018 in DevOps & Agile by ajs3033
• 7,040 points
56 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.