Reputation: 2983
I am writing a web application that expects a json file with the correct ordering of the json objects in a python list. It should be ordered x, y but no matter what I try, the values always return as y, x.
list: [{'y': 0.0, 'x': 1360633172168}, {'y': 0.0, 'x': 1360633172168}, ...
Can anyone shed some light on how to reorder these before writing the values out to the console?
label = ["x", "y"]
sen = []
for i in average:
now = int(round(time.time() * 1000))
l = now, i[0]
sen.append(l)
x = [dict(zip(label, e)) for e in sen]
I have tried several approaches to this and I get the same results every time.
Adam
Upvotes: 3
Views: 8272
Reputation: 114035
You might want to look into collections.OrderedDict
In [9]: d = collections.OrderedDict()
In [10]: d['x'] = 1360633172168
In [11]: d['y'] = 0.0
In [12]: d
Out[12]: OrderedDict([('x', 1360633172168), ('y', 0.0)])
In [13]: d['x']
Out[13]: 1360633172168
In [14]: d['y']
Out[14]: 0.0
Upvotes: 6
Reputation: 2718
The only solution would be to pass along an array, or store the order python side, of keys that are sorted and access the dict using that.
JSON:
{
"order": ["x", "y"],
"d": {x: 34, y:36}
}
PYTHON:
for key in order:
print d[key]
This will allow you to go through the dict keys in the proper order.
Dicts are a form of hash map and therefore they do not preserve key order.
Upvotes: 6
Reputation: 25569
If you really need to have keys in a specific order you will need to construct your "JSON" output manually as neither Python's dict
nor the json
module support fixed key ordering.
Upvotes: 0