Init a dictionary with a empty lists

Vlastimil Brom vlastimil.brom at gmail.com
Sat Feb 5 15:05:48 CET 2011


2011/2/5 Lisa Fritz Barry Griffin <lisaochbarry at gmail.com>:
> Hi there,
>
> How can I do this in a one liner:
>
>        maxCountPerPhraseWordLength = {}
>        for i in range(1,MAX_PHRASES_LENGTH+1):
>            maxCountPerPhraseWordLength[i] = 0
>
> Thanks!
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Hi,
as has been already suggested, using collections.defaultdict may be
appropriate, but it's fairly straightforward to mimic the original
code with a generator expression in dict(...)
maxCountPerPhraseWordLength = dict((i,0) for i in range(1,MAX_PHRASES_LENGTH+1))
or with a dict literal (in newer python versions)
maxCountPerPhraseWordLength = {i:0 for i in range(1,MAX_PHRASES_LENGTH+1)}

(possibly using xrange for larger dicts - in pyton 2)

hth,
  vbr



More information about the Python-list mailing list