如何将'namedtuple'结构与'pickle'一起使用?

时间:2016-04-13 12:21:10

标签: python python-2.7 pickle namedtuple

我使用

创建了字典元组
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)}

然后我想保存这些以防万一我可以在以后使用它:

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

我得到了一堆主要指向我的namedtuple结构的错误:

  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

是否有办法保留我的元组(键)或以便宜的方式记录我的数据,以便它们共存?

1 个答案:

答案 0 :(得分:0)

事实证明,我在两个不同的功能中定义代码。将它们结合起来很可能会解决问题。