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

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

Posted by: admin November 29, 2017 Leave a comment

Questions:

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?

Answers:

Passing [] as second argument to dict.fromkeys() gives a rather useless result – all values in the dictionary will be the same list object.

In Python 2.7 or above, you can use a dicitonary comprehension instead:

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

In earlier versions of Python, you can use

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

Questions:
Answers:

Use defaultdict instead:

from collections import defaultdict
data = defaultdict(list)
data[1].append('hello')

This way you don’t have to initialize all the keys you want to use to lists beforehand.

What is happening in your example is that you use one (mutable) list:

alist = [1]
data = dict.fromkeys(range(2), alist)
alist.append(2)
print data

would output {0: [1, 2], 1: [1, 2]}.

Questions:
Answers:

You are populating your dictionaries with references to a single list so when you update it, the update is reflected across all the references. Try a dictionary comprehension instead. See
Create a dictionary with list comprehension in Python

d = {k : v for k in blah blah blah}

Questions:
Answers:

You could use this:

data[:1] = [‘hello’]