[Tutor] Lists on the fly?

Kent Johnson kent37 at tds.net
Sat Dec 23 14:13:06 CET 2006


Luke Paireepinart wrote:
> I think a better way to do this is to check if 'Level_%i' is in your 
> dictionary already.
> so the loop becomes
> 
> Lev_List = {}
> for Element in Elements:
>     keystr = 'Level_%i' % Element['Level']
>     if not Lev_List.has_key(keystr):
>        Lev_List[keystr] = []
>     Lev_List[keystr].append(Element['Name'])

I am a fan of dict.setdefault() which has this logic built in:
Lev_List = {}
for Element in Elements:
     keystr = 'Level_%i' % Element['Level']
     Lev_List.setdefault(keystr, []).append(Element['Name'])

Also there is no need to create a string for the key, Element['Level'] 
is a fine key:
Lev_List = {}
for Element in Elements:
     Lev_List.setdefault(Element['Level'], []).append(Element['Name'])

Kent



More information about the Tutor mailing list