[Tutor] working with multiple sets

kevin parks kp8 at mac.com
Wed Sep 9 13:48:20 CEST 2009


This discussion is making my brain melt.

It is also showing how clever Bob was to do it the way he did... I  
found a solution that i think works, and think has not yet been  
suggested. I quarantined Bob's code into a black box ... and then cast  
the output as a plain old fashioned python built in dictionary on  
output. So now instead of printing the code Bob gave the collection is  
returned by the func.

Then i can cast it as a dict and pick over that dictionary as i wish.  
Here (as a bonus) I can transverse a range of keys that is inclusive  
of all my keys and also use python's get() dict method to also  
indicate index points (keys) that are empty.. which by default returns  
'None', which is also useful in this case to show me what is missing.  
But I also have to do some type testing tomfoolery since missing keys  
return None, which is a special type (and not a list like the  
others)... I wanted the value list sorted so... i did  if type(item)  
== type(foo): .... not sure if there is a betterererer way.

Anyway, this woiks.

--


#!/usr/bin/env python

import collections

def pscape():
     lookup = collections.defaultdict(list)
     k1 = [34, 39, 41, 42, 43, 44, 46, 48, 49, 50, 51, 54, 55, 56, 58,  
60, 61, 62, 63, 65, 66, 67, 68]
     k2 = [51, 56, 58, 63, 65, 68, 70, 72, 75, 77, 80, 82]
     y1 = [51, 53, 54, 56, 58, 60, 61, 63, 65, 66, 68, 70, 72, 73, 70,  
72, 73, 75, 77, 79, 80]
     sets = {'k1': set(k1), 'k2': set(k2), 'y1': set(y1)}
     for key, value in sets.items():
         for element in value:
             lookup[element].append(key)
     return lookup

def test():
     gamut = dict(pscape())
     # -- scaffolding
     #print "\n\n", type(gamut), "\n\n", gamut, "\n\n", gamut.keys()
     print "\n\n"
     foo = [1, 2, 3]
     for x in range(30, 85):
         item = gamut.get(x)
         if type(item) == type(foo):
             item.sort()
         print x, item
     print "\n\n"

if __name__ == "__main__":
     test()




More information about the Tutor mailing list