mysql数据库中dict的tuple的tuple [英] tuple of tuple of dict from mysql database
问题描述
我正在从python运行MySQL查询,该查询返回dict的元组,我们称之为结果.现在每个字典有3个键/值对作为元素,这3个元素之一是日期.现在,我想创建"dict元组"
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
(({},{},{}..),({},{},{}..),({},{},{}..)...)
其中每个内部元组表示同一日期的数据.我知道我可以用dict理解.但是我正在寻找更优雅的方式来做到这一点.我如何以最有效的方式做到这一点?
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 ?
推荐答案
一个不错的解决方案是将它们存储在字典中:
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.
这篇关于mysql数据库中dict的tuple的tuple的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!