Summary of three pythonic solutions to instantiating dictionaries. Having a "one-line" solution should never be the most important consideration.
1. Keys and default value defined in advance.
Instead of setting a default value for every key, use dict.fromkeys
. Also, do not name variables the same as classes, e.g. use lst
instead.
dic2 = dict.fromkeys(lst, 0)
2. Default value defined in advance, but not keys.
Alternatively, if you will be adding more keys in the future, consider using collections.defaultdict
, which is a subclass of dict
:
from collections import defaultdict
dic2 = defaultdict(int)
dic2['newkey'] # returns 0 even not explicitly set
3. Keys and values related by a function.
For building a dictionary where keys and values are linked via a function, use a dictionary comprehension, as described in detail by @OmerB, e.g.
{k: f(k) for k in lst} # value function of given keys
{f(v): v for v in lst} # key function of given values