1

I have created tuple of dictionary using

from collections import namedtuple
import random
demand={}
Site_Product=namedtuple("Site_Product", ["site", "product"])   
Products=['P1','P2','P3']    
for P in Products:
    for node in range(1,4): #Suppliers:
        sp=Site_Product(site=node, product=P)
        demand={sp:random.normalvariate(30, 25)}

Then I want to save these in case I might use it later on as follows:

import pickle
PIK = "pickle_SC_detail.dat"  
with open(PIK, "wb") as f:
    pickle.dump(demand, f)

I got a bunch of errors mainly pointing to my namedtuple structure:

  File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 1376, in dump
    Pickler(file, protocol).dump(obj)

  File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 224, in dump
    self.save(obj)

  File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self

  File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 655, in save_dict
    self._batch_setitems(obj.iteritems())

  File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 668, in _batch_setitems
    save(k)

  File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 331, in save
    self.save_reduce(obj=obj, *rv)

  File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 401, in save_reduce
    save(args)

  File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self

  File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 568, in save_tuple
    save(element)

  File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self

  File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 754, in save_global
    (obj, module, name))

PicklingError: Can't pickle \<class '__main__.Site_Product'\>: it's not found as __main__.Site_Product

Is there a work around either for keeping my dict of tuple(for keys) or recording my data in an inexpensive manner, so that they will coexist?

Ozgu
  • 151
  • 1
  • 12
  • copied your two code snippets, worked fine for me using Python 2.7.11 – PdevG Apr 13 '16 at 13:00
  • Code in question works for me using Python 2.7.11 on Windows. Are you sure `Site_Product` is defined at the top level (not inside a function or method) of your real code? – martineau Apr 13 '16 at 13:20
  • Yes, that must be the problem! They are in different functions, I will try to make namedtuple global or move them together. – Ozgu Apr 13 '16 at 13:22
  • The @MuhammadTahir is right and your question is a duplicate (and should be closed/deleted). – martineau Apr 13 '16 at 13:25

1 Answers1

0

It turned out, I was defining the codes in two different functions. Combining them will most likely solve the problem.

Ozgu
  • 151
  • 1
  • 12