Categories

See More
Popular Forum

MBA (4887) B.Tech (1769) Engineering (1486) Class 12 (1030) Study Abroad (1004) Computer Science and Engineering (988) Business Management Studies (865) BBA (846) Diploma (746) CAT (651) B.Com (648) B.Sc (643) JEE Mains (618) Mechanical Engineering (574) Exam (525) India (462) Career (452) All Time Q&A (439) Mass Communication (427) BCA (417) Science (384) Computers & IT (Non-Engg) (383) Medicine & Health Sciences (381) Hotel Management (373) Civil Engineering (353) MCA (349) Tuteehub Top Questions (348) Distance (340) Colleges in India (334)
See More

django raw query return non-ordered dict position according to select query

General Tech Bugs & Fixes

Max. 2000 characters
Tuteehub
Replies

usr_profile.png

User

( 7 months ago )

 

I have a query, for example select a, b, c, d from table. why does the dict return sometimes [{'b': 2}, {'a': 1}, {'d': 4}] ....] etc. I want it [{'a': 1}, {'b': 2}, {'c': 3}, ....] according to the position in the select query.

db.execute(query)
data = dictfetchall(db)
def dictfetchall(cursor):
    # Return all rows from a cursor as a dict
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]

usr_profile.png

User

( 7 months ago )

Dicts keys have been unordered in Python until version 3.6, where CPython's dict implementation keeps the insertion order, and in Python 3.7 dict order became officially guaranteed.

Since you're using Python 3.5, where dict keys are unordered, a typical alternative is to use collections.OrderedDict instead:

from collections import OrderedDict

def dictfetchall(cursor):
    columns = [col[0] for col in cursor.description]
    return [
        OrderedDict(zip(columns, row))
        for row in cursor.fetchall()
    ]

what's your interest


forum_ban8_5d8c5fd7cf6f7.gif