Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 344
Martin Burch Avatar asked Jul 16 '12 17:07

Martin Burch


People also ask

How do I create a list of empty dictionaries in Python?

Method #1 : Using {} + "*" operator We can create a list containing single empty dictionary and then multiply it by Number that is size of list. The drawback is that similar reference dictionaries will be made which will point to similar memory location.

How do you initialize an empty dictionary in Python?

How to Create An Empty Dictionary in Python. To create an empty dictionary, first create a variable name which will be the name of the dictionary. Then, assign the variable to an empty set of curly braces, {} . Another way of creating an empty dictionary is to use the dict() function without passing any arguments.

How do you initialize a dictionary in Python?

Another way to initialize a python dictionary is to use its built-in “dict()” function in the code. So, you have to declare a variable and assign it the “dict()” function as an input value. After this, the same print function is here to print out the initialized dictionary.


2 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)) 
like image 101
Sven Marnach Avatar answered Oct 05 '22 02:10

Sven Marnach


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]}.

like image 37
Martijn Pieters Avatar answered Oct 05 '22 02:10

Martijn Pieters