【发布时间】: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