我正在处理一组已转换为字典列表的数据
例如我列表中的一项是
{'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2005',
'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Bananas'}
根据要求
我列表中的第二项可能是:
{'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2006',
'actionDate': u'C20070627', 'data': u'86,000', 'rowLabel': u'Sales of Bananas'}
第三项可以是:
{'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2005',
'actionDate': u'C20070627', 'data': u'116,000', 'rowLabel': u'Sales of Cherries'}
第四项可以是:
{'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2006',
'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Sales of Cherries'}
我需要对其进行 pickle 的原因是,在合并结果并将它们放入数据库之前,我需要找出列的所有标记方式。第一项和第二项将是结果中的一行,第三项和第四项将是结果中的下一行(在有人决定统一列标题标签应该是什么之后)
我测试了 pickle 并且能够保存和检索我的数据。但是,我需要能够保留输出中的顺序。我的一个想法是添加另一个作为计数器的键,这样我就可以检索我的数据,然后按计数器排序。有没有更好的办法?
我不想将其放入数据库,因为它不是永久性的。
我在下面标记了一个答案。这不是我得到的,所以我需要弄清楚问题是否出在我的代码中的其他地方。
请您参考如下方法:
那么 pickle 有什么问题呢?如果您将数据结构化为字典列表,那么一切都应该按您希望的方式工作(如果我理解您的问题)。
>>> import pickle
>>> d1 = {1:'one', 2:'two', 3:'three'}
>>> d2 = {1:'eleven', 2:'twelve', 3:'thirteen'}
>>> d3 = {1:'twenty-one', 2:'twenty-two', 3:'twenty-three'}
>>> data = [d1, d2, d3]
>>> out = open('data.pickle', 'wb')
>>> pickle.dump(data, out)
>>> out.close()
>>> input = open('data.pickle')
>>> data2 = pickle.load(input)
>>> data == data2
True
