【问题标题】:Alternatives to Dictionary in Python - Need to reference value by named key and iterate in insertion orderPython中字典的替代方案 - 需要通过命名键引用值并按插入顺序迭代
【发布时间】:2012-10-26 19:54:44
【问题描述】:

我正在使用 Python 和 Django,并且将 JSON 对象作为 Python 字典返回,但我并不满足,因为我无法按照插入的顺序遍历字典的元素。

如果我按如下方式创建字典:

measurements = {
  'units': 'imperial',
  'fit': request.POST[ 'fit' ],
  'height': request.POST[ 'height' ],
  'weight': request.POST[ 'weight' ],
  'neck': request.POST[ 'neck' ],
  # further elements omitted for brevity
}

我可以尝试像这样迭代它:

for k,v in measurements.iteritems():
  print k, 'corresponds to ', v

结果是:

shoulders corresponds to  shoulders_val
weight corresponds to  weight_val
height corresponds to  height_val
wrist corresponds to  wrist_val
...

我也尝试使用 sorted(),它按字母顺序遍历我的元素

bicep corresponds to  bicep_val
chest corresponds to  chest_val
fit corresponds to  fit_val
height corresponds to  height_val
...

我是 Python 新手。我希望找到一些方法来通过命名键(如测量['units'])来引用我的字典元素,但仍然能够按照它们的创建顺序遍历这些元素。我知道那里有一个ordered dictionary module,但我想远离非标准包。任何其他标准 Python 数据结构(列表、数组等)是否允许我通过命名键以插入顺序和引用值进行迭代?

【问题讨论】:

    标签: python dictionary loops


    【解决方案1】:

    如果您使用的是 py2.7 或更高版本,您可以使用 collections.OrderedDict 来保留插入顺序。 这是标准库的一部分。对于旧版本,有一个 activestate recipe 浮动,您可以将其复制并用作您的包/模块的一部分。否则,标准库中没有任何东西可以做到这一点。

    您可以自己继承dict 并使其记住插入的顺序——例如将信息存储在一个列表中——但是当标准库中已经存在一些新版本的东西并且如果您想支持旧版本,可以随时复制/粘贴配方。


    请注意,如果您将字典传递给接受字典(__init__update)的字典方法,它们将无法正确排序:

    import collections
    dd = collections.OrderedDict({
      'units': 'imperial',
      'fit': 'fit' ,
      'height': [ 'height' ],
      'weight': [ 'weight' ],
      'neck': [ 'neck' ],
    })
    
    print( dd )  #Order not preserved
    
    
    #Pass an iterable of 2-tuples to preserve order.
    ddd = collections.OrderedDict([
      ('units', 'imperial'),
      ('fit', 'fit') ,
      ('height', [ 'height' ]),
      ('weight', [ 'weight' ]),
      ('neck', [ 'neck' ]),
    ])
    
    print( ddd ) #Order preserved
    

    【讨论】:

      【解决方案2】:

      OrderedDict 位于collections 模块中,这是核心 Python 发行版的重要组成部分(至少,正如 mgilson 指出的,在 2.7+ 中)。

      OrderedDict 默认在 CPython 2.7、3.1、3.2 和 3.3 中可用。它在 2.5、2.6 或 3.0 中不存在。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-04
        • 1970-01-01
        • 2011-12-21
        • 2022-11-25
        • 2013-07-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多