Appending to a list, which is value of a dictionary

Steve D'Aprano steve+python at pearwood.info
Sat Oct 15 12:16:53 EDT 2016


On Sat, 15 Oct 2016 11:35 pm, Uday J wrote:

> Hi,
> 
> Here is the code, which I would like to understand.
> 
>>>> l=['a','b','c']
>>>> bm=dict.fromkeys(l,['-1','-1'])

fromkeys() doesn't make a copy of the list each time it is used. It uses the
exact same list each time. Watch:

py> L = []
py> d = dict.fromkeys((1, 2, 3), L)
py> print(id(d[1]), id(d[2]), id(d[3]), id(L))
3081897484 3081897484 3081897484 3081897484


You get the same ID number four times: there's only one dict here, in four
places: L, d[1], d[2] and d[3] all refer to the same dict. So what what
happens:

py> print(d)
{1: [], 2: [], 3: []}
py> L.append('abc')
py> print(d)
{1: ['abc'], 2: ['abc'], 3: ['abc']}


That's because this is NOT four copies of the same list, but just the same
list, in four places.

Here are two options:

# Python 3 only: use a dict comprehension
py> d = {x:[] for x in (1, 2, 3)}
py> d
{1: [], 2: [], 3: []}
py> d[1].append('abc')
py> d
{1: ['abc'], 2: [], 3: []}


# any version of Python
d = {}
for x in (1, 2, 3):
    d[x] = []






-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list