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