# why in returns values for array and keys for dictionary

Erik Max Francis max at alcyone.com
Tue Aug 26 08:49:21 CEST 2008

```Marc 'BlackJack' Rintsch wrote:

> On Mon, 25 Aug 2008 19:57:06 -0700, alex23 wrote:
>
>> On Aug 26, 10:49 am, "++imanshu" <himanshu.g... at gmail.com> 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.
>> […]
>>
>> In both cases, 'in' returns a boolean indicating the existence of an
>> item in the list, or a key in the dict. I'm not sure why you'd need it
>> to return the item you're checking for the existence of, as you'd have
>> to have that item before you could do the check.
>>
>> Have I missed what you're asking for here? Could you provide a
>> pseudocode example to demonstrate what you mean?
>
> The OP isn't talking about the ``in`` operator but ``in`` as part of
> ``for … in …``.  So it's actually the question why ``list(a_dict)``
> doesn't return a list of values but a list of keys.

That is basically the same question.  Iterating over a list gives you
its elements, and using the `in` operator with lists tells you whether
or not an object is an element of the list.  Iterating over a dictionary
gives you its _keys_, not its values, and the `in` operator with
dictionaries tells you whether or not a _key_ is in the dictionary.

>>> l = [1, 2, 3]
>>> for x in l: print x
...
1
2
3
>>> 0 in l
False
>>> 1 in l
True
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for x in d: print x
...
a
c
b
>>> 'a' in d
True
>>> 1 in d
False

The reason why people find it more useful to deal with keys rather than
values of a dictionary during iteration or containment testing is ...
because that tends to be what you're usually more interested in, and is
more efficient.  For another thing, if you're doing a lot of testing for
containment in values, then it's likely you're not using the right data
structure, or combination of data structures.  That's not what
dictionaries are for.

--
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
Well I have been puppetized / Oh how I have compromised
-- Lamya

```