[Tutor] working with multiple sets

Lie Ryan lie.1296 at gmail.com
Wed Sep 9 05:22:29 CEST 2009


Alan Gauld wrote:
> 
> "kevin parks" <kp8 at me.com> wrote
>> What would this look like if i want to use a straight up built-in  
>> dictionary type and not the collections.defaultdict.
>>
> 
> Not too different:

Alternatively:

>> import collections
>>
>> def foo():
>> lookup = collections.defaultdict(list)
>> x = range(10)
>> y = range(5, 15)
>> z = range(8, 22)
>> sets = {'x': set(x), 'y': set(y), 'z': set(z)}
>> for key, value in sets.items():
>>         for element in value:
                try:
                    lookup[element] = lookup[element].append(key)
                except KeyError:
                    lookup[element] = [key]
>> print "\n", lookup, "\n\n"
>> for x in lookup:
>>      lookup[x].sort()
>>      print x, lookup[x]
>> print "\n"

which I /personally/ found easier to follow than using dict.get()'s or 
defaultdict (YMMV)



More information about the Tutor mailing list