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

dictionary, list, python

Solution

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))

Problem

My attempt to programmatically create a dictionary of lists is failing to allow me to individually address dictionary keys. Whenever I create the dictionary of lists and try to append to one key, all of them are updated. Here's a very simple test case: ``` data = {} data = data.fromkeys(range(2),[]) data[1].append('hello') print data ``` Actual result: `{0: ['hello'], 1: ['hello']}` Expected result: `{0: [], 1: ['hello']}` Here's what works ``` data = {0:[],1:[]} data[1].append('hello') print data ``` Actual and Expected Result: `{0: [], 1: ['hello']}` Why is the `fromkeys` method not working as expected?

Original source

Related problems