Reputation: 390
I am running MySQL query from python that returning tuple of dict, lets call it result. Now each dict has 3 key/value pairs as an element, one of these 3 element is date. Now I want to create "tuple of tuple of dict" something like
(({},{},{}..),({},{},{}..),({},{},{}..)...)
where each inner tuple represent the data of the same date. I know i can use dict comprehension. But am looking for more elegant way to do this. How can I do this in most efficient way ?
Upvotes: 0
Views: 378
Reputation: 5090
One good looking solution would be to store them inside a dictionary:
>>> t = ({"a":2}, {"a":2}, {"a":3})
>>> import collections
>>> d = collections.defaultdict(list)
>>> for i in t:
... d[i['a']].append(i)
...
Now, this is obviously not what you want but this is better than creating the list of lists inside a loop directly in terms of speed, also a dictionary seems to be a better fit for this kind of data. This can also be converted to whatever you want easily:
>>> [k for c,k in d.items()]
[[{'a': 2}, {'a': 2}], [{'a': 3}]]
If the speed is critical, you can sort the db results by date, in which case you can get a better algorithm.
Upvotes: 1