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.
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]}
Maybe a dict comprehension?
newdict = {x: [] for x in range(10)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With