tuple of tuple of dict from mysql database

断了今生、忘了曾经 提交于 2019-12-11 18:10:10

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/40782777/tuple-of-tuple-of-dict-from-mysql-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!