Creating dictionary of dictionaries in python 2.6

坚强是说给别人听的谎言 提交于 2019-12-09 02:07:24

问题


I have a line of code in python2.7 that generates a dictionary of empty dictionaries:

values=[0,1,2,4,5,8] 
value_dicts={x:{} for x in values}

which throws a syntax error when run on python2.6.

I can do the same thing using a for loop:

values_dicts={}
values=[0,1,2,4,5,8]
for value in values :
values_dicts[value]={}
values_dicts
Out[25]: {0: {}, 1: {}, 2: {}, 4: {}, 5: {}, 8: {}}

But that seems silly. Why does the list comprehension (in the first block) not work in python2.6?


回答1:


You can use the dict() constructor:

value_dicts = dict((x, {}) for x in values)

This uses a generator expression that constructs (key, value) tuples, which the dict() constructor is happy to turn into a dictionary for you.

Demo:

>>> values=[0,1,2,4,5,8] 
>>> dict((x, {}) for x in values)
{0: {}, 1: {}, 2: {}, 4: {}, 5: {}, 8: {}}

The syntax you used (a dict comprehension) was not introduced until Python 2.7 and Python 3, see PEP 274.




回答2:


Depending on your intended use, you could also just use a defaultdict instead.

from collections import defaultdict
value_dicts = defaultdict(lambda: defaultdict(int))


来源:https://stackoverflow.com/questions/16221368/creating-dictionary-of-dictionaries-in-python-2-6

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