S
S
Sergey Eremin2016-02-03 13:33:27
Django
Sergey Eremin, 2016-02-03 13:33:27

How to transpose a QuerySet or turn a list (array) of dictionaries into a dictionary of lists (arrays)?

Actually the question says it all. A big-tricky raw request is made. We get a QuerySet, but we need to display it not by row, but by column... For example:

qSetKit = SetKit.objects.raw("SELECT ... ... ...")
listSetKit = list(qSetKit)
print listSetKit

Gives, say, the following list of dictionaries:
[
    { "Aaa": 1, "Bbb": 100, "Ccc": 22, "Ddd": u"red"},
    { "Aaa": 10, "Bbb": 101, "Ccc": 0, "Ddd": u"pink"},
    { "Aaa": 0, "Bbb": 6, "Ccc": 0, "Ddd": u"snowwhite"}
]

And you need to get a dictionary of lists:
{ 
   "Aaa": [1, 10, 0],
   "Bbb": [100, 101, 6],
   "Ccc": [22, 0, 0],
   "Ddd": [u"red", u"pink", u"snowwhite"]
}

It is clear that all this can be done in a cycle (especially since for some resulting lists in the dictionary in my case it is necessary to find all sorts of average metrics, for others the deviation, for the third something else) ... But out of sports interest, I want to know a universal solution . There are not many lists in the dictionary with which something will have to be done additionally. Only 15-20%. The rest are thrown into the template without change. But the keys themselves in the resulting dictionary are very dofiga! To drive them in a cycle from an array of lists to an array list is not rational and resource-intensive. I would like to avoid this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
r1ch, 2016-02-05
@r1ch

DEMO HERE

def pluck(coll):
    coll_keys = {}
    
    for i in coll:
        coll_keys.update(i)
    
    new_coll = {}
    
    for i in coll_keys.keys():
        new_coll[i] = []
        
    for i in coll:    
        for j in new_coll:
            if j in i:
                new_coll[j].append(i[j])

    return new_coll

print pluck([
    {'Aaa': 1, 'Bbb': 100, 'Ccc': 22, 'Ddd': u'red'},
    {'Aaa': 10, 'Bbb': 101, 'Ccc': 0, 'Ddd': u'pink'},
    {'Aaa': 0, 'Bbb': 6, 'Ccc': 0, 'Ddd': u'snowwhite'}
])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question