Creating a nested dictionary comprehension in Python 2.7

一个人想着一个人 提交于 2019-12-11 18:26:53

问题


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]))

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.


回答1:


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


来源:https://stackoverflow.com/questions/9239130/creating-a-nested-dictionary-comprehension-in-python-2-7

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