I am using Python and Django and messing around with returning JSON objects as Python dictonaries, but am not content because I can’t iterate through my dictionary’s elements in the order they were inserted.
If I create a dictionary as follows:
measurements = {
'units': 'imperial',
'fit': request.POST[ 'fit' ],
'height': request.POST[ 'height' ],
'weight': request.POST[ 'weight' ],
'neck': request.POST[ 'neck' ],
# further elements omitted for brevity
}
I can try iterating through it like:
for k,v in measurements.iteritems():
print k, 'corresponds to ', v
The result is:
shoulders corresponds to shoulders_val
weight corresponds to weight_val
height corresponds to height_val
wrist corresponds to wrist_val
...
I also tried using sorted(), which iterates through my elements by key alphabetically
bicep corresponds to bicep_val
chest corresponds to chest_val
fit corresponds to fit_val
height corresponds to height_val
...
I am new to Python. I am hoping to find some way to both reference my dictionary elements by named keys like measurements[‘units’] but still be able to iterate through these elements in the order they were created. I am aware that there is an ordered dictionary module out there, but I would like to stay away from nonstandard packages. Would any other standard Python data structures ( lists, arrays, etc. ) allow me to iterate in insertion order and reference values by named keys?
You can use a
collections.OrderedDictto preserve insertion order if you’re using py2.7 or newer. This is a part of the standard library. For older versions, there’s an activestate recipe floating around that you could copy and use as part of your package/module. Otherwise, there’s nothing in the standard library that will do it.You could subclass
dictyourself and make it so the it remembers the order things were inserted — storing the information in a list for instance — but that is overkill when something already exists in the standard library for newer versions and a recipe that you can copy/paste is readily available if you want to support old versions.Note that dictionary methods which accept dictionaries (
__init__,update) won’t be sorted properly if you pass dictionaries to them: