【问题标题】:Does anyone know where there is a recipe for serializing data and preserving its order in the output?有谁知道哪里有序列化数据并在输出中保留其顺序的方法?
【发布时间】:2010-09-24 00:56:18
【问题描述】:

我正在处理一组已转换为字典列表的数据

例如,我列表中的一项是

{'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,并且能够保存和检索我的数据。但是,我需要能够保留输出中的顺序。我的一个想法是添加另一个作为计数器的键,这样我就可以检索我的数据,然后按计数器排序。有没有更好的办法?

我不想将它放入数据库,因为它不是永久性的。

我在下面标记了一个答案。这不是我得到的,所以我需要弄清楚问题是否在我的代码中的其他地方。

【问题讨论】:

  • 显示多行怎么样?如果有多行并且您希望在各行之间保留顺序,那么一个更好的示例将有助于解释事情。

标签: python serialization


【解决方案1】:

Python 不保留字典中的顺序。
但是,collections 模块中有OrderedDict 类。

另一种选择是使用元组列表:

[('reportDate', u'R20080501'), ('idnum', u'1078099'), ...etc]

如果您以后需要将其转换为字典,可以使用内置的dict()

【讨论】:

    【解决方案2】:

    那么泡菜有什么问题呢?如果您将数据构建为字典列表,那么一切都应该按照您的意愿工作(如果我理解您的问题)。

    >>> 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
    

    【讨论】:

      【解决方案3】:

      Python dict 是一个无序容器。如果您需要保留条目的顺序,则应考虑使用 2 元组列表。

      另一种选择是保留一个额外的有序键列表。通过这种方式,您可以从字典提供的快速、键控访问中受益,同时仍然能够以有序的方式遍历其值:

      data = {'reportDate': u'R20070501', 'idnum': u'1078099', 
              'columnLabel': u'2005', 'actionDate': u'C20070627', 
              'data': u'76,000', 'rowLabel': u'Sales of Bananas'}
      dataOrder = ['reportDate', 'idnum', 'columnLabel', 
                   'actionDate', 'data', 'rowLabel']
      
      for key in dataOrder:
          print key, data[key]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-27
        • 2016-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-12
        • 1970-01-01
        相关资源
        最近更新 更多