Creating dictionary of dictionaries in python 2.6

后端 未结 2 1369
遇见更好的自我
遇见更好的自我 2021-01-07 09:13

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}
2条回答
  •  有刺的猬
    2021-01-07 09:38

    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.

提交回复
热议问题