在Python 2.7中创建嵌套的字典理解 [英] Creating a nested dictionary comprehension in Python 2.7
问题描述
我有一个从MySQL cursor.fetchall()返回的嵌套元组,其中包含一些结果,格式为(datetime.date,float).我需要将它们分离成 [month/year] [month of day] 形式的嵌套字典-因此,我希望有一个字典(例如)读物,例如em> readings ['12/2011'] [13] 即可获取"12/2011"月份第13天的读数.这样做是为了生成图形,以显示覆盖多个月的每日读数.
I have a nested tuple returned from a MySQL cursor.fetchall() containing some results in the form (datetime.date, float). I need to separate these out in to a nested dictionary of the form [month/year][day of month] - so I would like to have a dictionary (say) readings which I would reference like readings['12/2011'][13] to get the reading for 13th day of the month '12/2011'. This is with a view to producing graphs showing the daily readings for multiple months overlaid.
我的困难是(我相信)我需要使用唯一的月/年标识符设置字典的第一个维度.我目前通过以下方式获取这些列表:
My difficulty is that (I believe) I need to set up the first dimension of the dictionary with the unique month/year identifiers. I am currently getting a list of these via:
list(set(["%02d/%04d" % (z[0].month, z[0].year) for z in raw]))
其中raw是从数据库返回的元组列表.
where raw is a list of tuples returned from the database.
现在,我可以轻松地将其分为两个阶段进行-设置字典的第一个维度,然后再次遍历数据以设置第二个.我想知道是否有一种可读的方式可以同时使用嵌套的字典/列表理解来同时完成两个步骤.
Now I can easily do this as a two stage process - set up the first dimenion of the dictionary then go through the data once more to set-up the second. I wondered though if there is a readable way to do both steps at once possibly with nested dictionary/list comprehensions.
如果有任何建议,我将不胜感激.谢谢.
I'd be graetful for any advice. Thank you.
推荐答案
要在简洁的Oneliner中同时完成两个级别似乎很困难,我建议您改用
it seems difficult to do both levels in a concise oneliner, I propose you instead to use defaultdict
like this:
res = defaultdict(dict)
for z in raw:
res["%02d/%04d"%(z[0].month, z[0].year)][z[0].day] = z
这篇关于在Python 2.7中创建嵌套的字典理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!