How to initialize an empty list dictionary in Python?

My attempt to programmatically create a dictionary of lists does not allow me to individually access the dictionary keys. Whenever I create a dictionary of lists and try to add one key, they are all updated. Here is 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']}

Works here

 data = {0:[],1:[]} data[1].append('hello') print data 

Actual and expected result: {0: [], 1: ['hello']}

Why fromkeys method fromkeys work as expected?

+76
python dictionary list
Jul 16 2018-12-17T00:
source share
4 answers

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

In Python 2.7 or later, you can use 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)) 
+90
Jul 16 '12 at 17:50
source share

Use defaultdict instead:

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

This way, you do not need to pre-initialize all the keys that you want to use in the lists.

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

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

outputs {0: [1, 2], 1: [1, 2]} .

+67
Jul 16 '12 at 17:50
source share

You fill out dictionaries with links to one list, so when it is updated, the update is reflected in all links. Try using a dictionary instead. See Create a List Dictionary in Python

 d = {k : v for k in blah blah blah} 
+7
Jul 16 '12 at 17:50
source share

You can use this:

data [: 1] = ['hello']

-3
Jun 15 '17 at 17:44
source share



All Articles