Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a dict of blank lists that are not the same list [duplicate]

I am trying to create a dict of lists that can be appended to in a for loop. However, if I create a dict using fromkeys, the list becomes a copy of a "pointer", not a new list. For example,

newdict = dict.fromkeys(range(10), [])

-- or --

newdict = dict.fromkeys(range(10), list())

both yield the same data structure, a dict with the SAME list as the value pair. So that when any key is updated e.g. - newdict[0].append(100), the corresponding output of print newdict is:

{0: [100], 1: [100], 2: [100], 3: [100], 4: [100], 5: [100], 6: [100], 7: [100], 8: [100], 9: [100]}

Any thoughts on how to avoid this without having to iterate through in a for loop? Thanks in advance.

like image 786
paulski Avatar asked Jan 12 '23 15:01

paulski


2 Answers

The two most common approaches are to use a dict comprehension:

>>> d = {k: [] for k in range(10)}
>>> d[3].append(100)
>>> d
{0: [], 1: [], 2: [], 3: [100], 4: [], 5: [], 6: [], 7: [], 8: [], 9: []}

Or to use a defaultdict and forego setting any keys at all:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d
defaultdict(<type 'list'>, {})
>>> d[9].append(100)
>>> d
defaultdict(<type 'list'>, {9: [100]})

As a third option, by using setdefault -- e.g. d.setdefault(k, []) instead of d[k], like in the defaultdict case, you can avoid needing to preset []:

>>> d = {}
>>> d.setdefault(3, []).append(100)
>>> d
{3: [100]}
like image 137
DSM Avatar answered Jan 30 '23 21:01

DSM


Maybe a dict comprehension?

newdict = {x: [] for x in range(10)}
like image 33
Xymostech Avatar answered Jan 30 '23 23:01

Xymostech