Init a dictionary with a empty lists

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Feb 5 09:38:36 EST 2011


On Sat, 05 Feb 2011 14:38:29 +0100, Daniel Urban wrote:

> On Sat, Feb 5, 2011 at 14:08, Lisa Fritz Barry Griffin
> <lisaochbarry at gmail.com> wrote:
>> Hi there,
>>
>> How can I do this in a one liner:
>>
>>        maxCountPerPhraseWordLength = {}
>>        for i in range(1,MAX_PHRASES_LENGTH+1):
>>            maxCountPerPhraseWordLength[i] = 0
> 
> maxCountPerPhraseWordLength = {0 for i in range(1,MAX_PHRASES_LENGTH+1)}

Unfortunately not. In versions before Python 2.7, it will give a 
SyntaxError. In 2.7 or better it gives a set instead of a dict:

>>> MAX_PHRASES_LENGTH = 5
>>> maxCountPerPhraseWordLength={0 for i in range(1,MAX_PHRASES_LENGTH+1)}
>>> maxCountPerPhraseWordLength
set([0])


This will do the job most simply:

>>> dict(zip(range(1, MAX_PHRASES_LENGTH+1), [0]*MAX_PHRASES_LENGTH))
{1: 0, 2: 0, 3: 0, 4: 0, 5: 0}


Or this:

>>> dict((i, 0) for i in range(1, MAX_PHRASES_LENGTH+1))
{1: 0, 2: 0, 3: 0, 4: 0, 5: 0}


But perhaps the most simple solution is to just leave the dict empty, and 
instead of fetching items with dict[i], use dict.get(i, 0) or 
dict.setdefault(i, 0).



-- 
Steven



More information about the Python-list mailing list