Handling 2.7 and 3.0 Versions of Dict

Travis Parks jehugaleahsa at gmail.com
Thu Sep 1 03:28:09 CEST 2011


On Aug 31, 7:37 pm, Gregory Ewing <greg.ew... at canterbury.ac.nz> wrote:
> Ian Kelly wrote:
> > if sys.version_info < (3,):
> >     getDictValues = dict.itervalues
> > else:
> >     getDictValues = dict.values
>
> > (which is basically what the OP was doing in the first place).
>
> And which he seemed to think didn't work for some
> reason, but it seems fine as far as I can tell:
>
> Python 2.7 (r27:82500, Oct 15 2010, 21:14:33)
> [GCC 4.2.1 (Apple Inc. build 5664)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> gv = dict.itervalues
>  >>> d = {1:'a', 2:'b'}
>  >>> gv(d)
> <dictionary-valueiterator object at 0x2aa210>
>
> % python3.1
> Python 3.1.2 (r312:79147, Mar  2 2011, 17:43:12)
> [GCC 4.2.1 (Apple Inc. build 5664)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> gv = dict.values
>  >>> d = {1:'a', 2:'b'}
>  >>> gv(d)
> dict_values(['a', 'b'])
>
> --
> Greg

My problem was that I didn't understand the scoping rules. It is still
strange to me that the getValues variable is still in scope outside
the if/else branches.



More information about the Python-list mailing list