Dictionary with values of empty list

Question:

I want to create a dictionary with keys of 1, 2, 3, 4
and each value to the key is [].

n = [1,2,3,4]
d = dict.fromkeys(n, [])

d[1].append(777)

print(d)

--> {1: [777], 2: [777], 3: [777], 4: [777]}

Why does this happen? Why is this not {1: [777], 2: [], 3: [], 4: []} ?

Asked By: HREngineer

||

Answers:

The list that you use as values in the second step all point to the same memory. So when you update one of the values, all of them update.

You can check that by using the following –

n = [1,2,3,4]
d = dict.fromkeys(n, [])

d[1] is d[2] #share memory

#True

So, one way you can instead do the following –

n = [1,2,3,4]
d = {k:[] for k in n}

d[1] is d[2]

#False

Then you can set then –

d[1].append(777)

{1: [777], 2: [], 3: [], 4: []}

A better way to do this is to use collections.defaultdict. This allows you to create a dictionary where values are list objects by default using defaultdict(list). Its scalable as you can choose which datatype you need your dictionary values to be.

from collections import defaultdict

n = [1,2,3,4]
d = defaultdict(list)

d[1].append(777)
Answered By: Akshay Sehgal