How to initialize a dict with keys from a list and empty value in Python?
dict.fromkeys
directly solves the problem:
>>> dict.fromkeys([1, 2, 3, 4])
{1: None, 2: None, 3: None, 4: None}
This is actually a classmethod, so it works for dict-subclasses (like collections.defaultdict
) as well.
The optional second argument, which defaults to None
, specifies the value to use for the keys. Note that the same object will be used for each key, which can cause problems with mutable values:
>>> x = dict.fromkeys([1, 2, 3, 4], [])
>>> x[1].append('test')
>>> x
{1: ['test'], 2: ['test'], 3: ['test'], 4: ['test']}
Use a dict comprehension:
>>> keys = [1,2,3,5,6,7]
>>> {key: None for key in keys}
{1: None, 2: None, 3: None, 5: None, 6: None, 7: None}
The value expression is evaluated each time, so this can be used to create a dict with separate lists (say) as values:
>>> x = {key: [] for key in [1, 2, 3, 4]}
>>> x[1] = 'test'
>>> x
{1: 'test', 2: [], 3: [], 4: []}