why in returns values for array and keys for dictionary

Lie Lie.1296 at gmail.com
Tue Aug 26 09:00:25 EDT 2008


On Aug 26, 4:04 pm, "++imanshu" <himanshu.g... at gmail.com> wrote:
> On Aug 26, 11:52 am, Erik Max Francis <m... at alcyone.com> wrote:
>
> > ++imanshu wrote:
> > >     Wouldn't it be nicer to have 'in' return values (or keys) for both
> > > arrays and dictionaries. Arrays and Dictionaries looked so similar in
> > > Python until I learned this difference.
>
> > It's because dealing with keys makes far more sense, since that's how
> > the dictionary data structure works.  If you're doing this an awful lot
> > -- whether testing for inclusion or iterating -- then you're probably
> > using the wrong data structure.
>
> Thanks for the detailed replies. Python seems to be taking the
> pragmatic approach here instead of the pure one. And yes it makes more
> sense.

Anyway, there is two obvious choice when dealing with dictionary
looping: return the keys and return the key and value. The python
designer thought that it is trivial to get the value from key so
returning both key and value, when the value might not be used at all,
is redundant and might cause a slow down. In the case where it is
actually needed for practicality (usually one-liner), then
dict.iteritems() is provided, in other cases where you don't need the
key (usually when you're applying a uniform function to dictionary or
to convert it to a list), dict.itervalues() is provided, and for
completeness dict.iterkeys() which is completely useless in a for-loop
is provided (the only case where it _might_ be useful is in
callbacks).

Anyway, in short (in code):
for key in dict:
    print key, dict[key]

is exactly the same as:
for key, value in dict.iteritems():
    print key, value

or
for key in dict:
    value = dict[key]
    print key, value
    # the next line is not needed if you don't modify an immutable
value
    dict[key] = value



More information about the Python-list mailing list