[Baypiggies] Tricky dictionary iteration problem

Jason Culverhouse jason at mischievous.org
Fri Jan 6 02:23:26 CET 2012


On Jan 5, 2012, at 4:57 PM, corey.coughlin at comcast.net wrote:

> Hi all,
>    Sorry to bug everybody, but I'm having some trouble with a somewhat tricky class I'm trying to make.  I have a class that inherits from collections.OrderedDict, in an effort to create an ordered dictionary with some extra functions.  Now what I'd like to do is to change the iteration so that when you iterate over it, it iterates over values instead of keys.  This is turning out to be harder than I thought.  First, I tried this:
> 
> class od2(collections.OrderedDict):
>     def __iter__(self):
>         return iter(self.values())

I know I'm confused about what you want to do here... perhaps a code sample would be better but I'm thinking you just want itervalues?
(An aside but I don't think anything happened along the lines of http://www.python.org/dev/peps/pep-3106/ )

>>> import collections
>>> d = collections.OrderedDict([(1,'one'), (2, 'two'), (3, 'three'), (4, 'four')])
>>> d
OrderedDict([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')])
>>> d.values()
['one', 'two', 'three', 'four']
>>> [v for v in d.itervalues()]
['one', 'two', 'three', 'four']

It would be quite confusing for one to write the following and not get anything but
>>> [k for k in d]
[1, 2, 3, 4]


> and list() uses the iterator.  Gah.  So I'm out of ideas here, even if I dig into OrderedDict and find some way to pull the keys out, I'll probably have to rewrite a bunch of access functions for it to still work like a dictionary.  Am I just tilting at windmills, or is doing something like this actually possible?  Or am I just being dense, and there's a super obvious way to do this? Thanks for any help!
> 
> (Oh, and forgive me if there's a known fix for this, googling for anything along these lines just sent me to tons of tutorials about using the .values() function.  No help there.)
> 
>       ------- Corey
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies


Jason



More information about the Baypiggies mailing list