[Tutor] working with multiple sets
Douglas Philips
dgou at mac.com
Tue Sep 8 19:58:12 CEST 2009
On or about 2009 Sep 8, at 1:51 PM, Alan Gauld indited:
> "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:
>
>> import collections
>> def foo():
>> lookup = collections.defaultdict(list)
# Doug: lookup = dict()
>> 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:
> lookup[element] = lookup.get(element, []).append(key)
# Doug: That doesn't do what you think it does, it won't insert the
new list into the dictionary.
# Doug: I think what you want is lookup.setdefault(element,
[]).append(key)
>> print "\n", lookup, "\n\n"
>> for x in lookup:
>> lookup[x].sort()
>> print x, lookup[x]
>> print "\n"
>
> At least I think thats all you need here.
>>> help(dict.setdefault)
setdefault(...)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
-Doug
-Doug
More information about the Tutor
mailing list