Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dict ordering

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

like image 888
aeupinhere Avatar asked Feb 27 '26 21:02

aeupinhere


2 Answers

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.

like image 153
dennmat Avatar answered Mar 01 '26 10:03

dennmat


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
like image 44
inspectorG4dget Avatar answered Mar 01 '26 10:03

inspectorG4dget



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!