[Tutor] Lists on the fly?

Luke Paireepinart rabidpoobear at gmail.com
Sat Dec 23 20:44:37 CET 2006

Kent Johnson wrote:
> Luke Paireepinart wrote:
>> I think a better way to do this is to check if 'Level_%i' is in your 
>> dictionary already.
> 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:
You're absolutely right, Kent.
I just created a variable for it because I referred to it 3 times, and 
didn't want to write out the string over and over.
The only reason I used 'Level_%i' instead of just Element['Level'] was 
because he had that in the original program.
> Lev_List = {}
> for Element in Elements:
>      Lev_List.setdefault(Element['Level'], []).append(Element['Name'])
Really cool.
I'm a fan now, too :)
Thanks for this.


More information about the Tutor mailing list