元祖数据mysql,mysql数据库中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

(({},{},{}..),({},{},{}..),({},{},{}..)...)

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值