Init a dictionary with a empty lists

Peter Otten __peter__ at web.de
Sat Feb 5 08:36:41 EST 2011


Lisa Fritz Barry Griffin wrote:

> How can I do this in a one liner:
> 
>         maxCountPerPhraseWordLength = {}
>         for i in range(1,MAX_PHRASES_LENGTH+1):
>             maxCountPerPhraseWordLength[i] = 0

You can init a dictionary with zeroes with

d = dict.fromkeys(range(1, MAX_PHRASES_LENGTH+1), 0)

but this won't work as expected for mutable values:

>>> d = dict.fromkeys(range(5), [])
>>> d
{0: [], 1: [], 2: [], 3: [], 4: []}
>>> d[0].append(42)
>>> d
{0: [42], 1: [42], 2: [42], 3: [42], 4: [42]}

Oops! all values refere to the same list.
Instead you can use a defaultdict which adds items as needed:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d
defaultdict(<type 'list'>, {})
>>> d[0].append(42)
>>> d
defaultdict(<type 'list'>, {0: [42]})
>>> d[7].append(123)
>>> d
defaultdict(<type 'list'>, {0: [42], 7: [123]})




More information about the Python-list mailing list