Answer the question
In order to leave comments, you need to log in
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
[
{ "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"}
]
{
"Aaa": [1, 10, 0],
"Bbb": [100, 101, 6],
"Ccc": [22, 0, 0],
"Ddd": [u"red", u"pink", u"snowwhite"]
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question