Python中Dictionary的替代方法 – 需要通过命名键引用值并按插入
发布时间:2020-12-20 12:21:15 所属栏目:Python 来源:网络整理
导读:我正在使用 Python和Django,并将返回的JSON对象作为Python dictonaries,但我并不满足,因为我无法按插入顺序遍历我的字典元素. 如果我按如下方式创建字典: measurements = { 'units': 'imperial','fit': request.POST[ 'fit' ],'height': request.POST[ 'hei
我正在使用
Python和Django,并将返回的JSON对象作为Python dictonaries,但我并不满足,因为我无法按插入顺序遍历我的字典元素.
如果我按如下方式创建字典: 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数据结构(列表,数组等)是否允许我通过命名键迭代插入顺序和引用值? 解决方法
如果您使用的是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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |