Actually,

This seems like it works:

                lookup[x].sort()


in like so:

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:
                        lookup[element].append(key)
        print
        print lookup, "\n\n"
        for x in lookup:
                lookup[x].sort()
                print x, lookup[x]
                #print type(lookup)
        print
        #print sets

I realized that i was trying to apply the standard:

        k = lookup.keys()
        k.sort()

in the wrong way and in the wrong place (i accidentally cut it out in my message when i removed the scaffolding)

I might try the tuple things to for educational purposes. I am somewhat nervous about using something other than a built in type as i am not familiar with collections and it isn't well covered in beginner books or the docs.



On Sep 9, 2009, at 12:44 AM, Kent Johnson wrote:

On Tue, Sep 8, 2009 at 10:07 AM, kevin parks<k...@me.com> wrote:
I also notice that if i do:


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:
                       lookup[element].append(key)
       for x in lookup:
               print x, lookup[x]
       print

in oder to print more clearly what I want to see, the sets (as usual for a mapping type) are not always in order. Note that from 5 to 7 for example 'y' is listed in front of 'x' and 8 & 9 have 'y', 'x', 'z' and not 'x', 'y', 'z'

Dictionaries and sets are not ordered. The order of items in
sets.items() is an implementation detail, not something you can depend
on.

... I am not clear on how to sort that as the dictionary      method
lookup.sort() either doesn't work or i have tried it in all the wrong
places.

lookup can't be sorted directly as it is a (default)dict. Anyway it is
lookup[x] that you want to sort. Try
 print x, sorted(lookup[x])

or
for x in lookup:
 lookup[x].sort() # list.sort() sorts the list in place and does not
return a value.
 print x, lookup[x]

Another alternative would be to use a list of tuples instead of a dict
for sets, then the lookup values would be created in the desired
order, e.g.
sets = [ (x', set(x)), ('y', set(y)), ('z', set(z)) ]
for key, value in sets:
 # etc

Kent

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to