Serge
Serge

Reputation: 1497

SqlAlchemy sorting issue

For some reason Im using SqlAlchemy with custom queries:

sql = "SELECT id, shooter_id, value FROM points WHERE match_id = %s ORDER BY value" % match_id
rows = self._session.execute(sql).fetchall()
for (shooter_id, value) in rows:
  r[shooter_id] = value

with this query i've got this data:

1 100 5.5
3 101 6.4
2 121 8.2

Not a big deal and it works good on my development PC with Windows, Python 3.6.0 and MariaDb. But when I deploy application to debian jessie with Python 3.4.2 and Mysql problems come: data stop being sorted. In other words I've got:

1 100 5.5
2 121 8.2
3 101 6.4

Unsorted!

All libaries are the same versions and I have no idea where to look to solve this. Okay, I have different pyton version and DB engine but I dont think it is that.

Help!

Upvotes: 1

Views: 243

Answers (1)

Szabolcs Dombi
Szabolcs Dombi

Reputation: 5783

You store the returned data in a dictionary and when you print the dictionary you get the result in a random order. Use the following snippet to print your dictionary properly:

for key in sorted(r.keys()):
    print(key, r[key])

If you use OrderedDict python will remember the order you entered the keys.

Upvotes: 1

Related Questions