How do I initialize a dictionary of empty lists in Python?

When [] is passed as the second argument to dict.fromkeys(), all values in the resulting dict will be the same list object.

In Python 2.7 or above, use a dict comprehension instead:

data = {k: [] for k in range(2)}

In earlier versions of Python, there is no dict comprehension, but a list comprehension can be passed to the dict constructor instead:

data = dict([(k, []) for k in range(2)])

In 2.4-2.6, it is also possible to pass a generator expression to dict, and the surrounding parentheses can be dropped:

data = dict((k, []) for k in range(2))

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)