Jam*_*ton 3 python dictionary loops
我正在使用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
}
Run Code Online (Sandbox Code Playgroud)
我可以尝试迭代它,如:
for k,v in measurements.iteritems():
print k, 'corresponds to ', v
Run Code Online (Sandbox Code Playgroud)
结果是:
shoulders corresponds to shoulders_val
weight corresponds to weight_val
height corresponds to height_val
wrist corresponds to wrist_val
...
Run Code Online (Sandbox Code Playgroud)
我也尝试使用sorted(),按字母顺序按键遍历我的元素
bicep corresponds to bicep_val
chest corresponds to chest_val
fit corresponds to fit_val
height corresponds to height_val
...
Run Code Online (Sandbox Code Playgroud)
我是Python的新手.我希望找到某种方法来通过命名键来引用我的字典元素,例如测量['单位'],但仍然能够按照它们创建的顺序迭代这些元素.我知道有一个有序的字典模块,但我想远离非标准的包.任何其他标准Python数据结构(列表,数组等)是否允许我通过命名键迭代插入顺序和引用值?
collections.OrderedDict如果您使用的是py2.7或更新版本,则可以使用a 来保留插入顺序. 这是标准库的一部分.对于旧版本,有一个activestate配方可以复制并作为包/模块的一部分使用.否则,标准库中没有任何内容可以执行此操作.
您可以dict自己进行子类化并使其成为记住插入事物的顺序 - 例如将信息存储在列表中 - 但是当标准库中已存在某些内容以用于较新版本并且您可以复制的配方时,这样就太过分了如果您想支持旧版本,可以随时使用/ paste.
请注意,如果您将字典传递给它们,则接受字典(__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
Run Code Online (Sandbox Code Playgroud)
OrderedDict是在collections模块中的,该模块是Python核心发行版的很大一部分(至少,如mgilson所指出的那样,在2.7+中)。
默认情况下,OrderedDict在CPython 2.7、3.1、3.2和3.3中可用。它在2.5、2.6或3.0中不存在。