More random python observations from a perl programmer
Patrick Bogaart
bogw at geo.vu.nl
Fri Aug 20 05:20:00 EDT 1999
Jeff Blaine wrote:
>
> >GOTCHA: (low)
> > You can't use "in" on dicts. Instead, you must use
> > d = { "fred":"wilma", "barney":"betty" }
> > if d.has_key("fred"): # legal
> > if "fred" in d: # ILLEGAL
> > I don't understand why this was done.
>
> I'm very curious what would you think should be legal.
>
> Would 'in' (when used on a dict) search the keys, values, or both?
>
> Each one of those seem like a bad idea to me. You have 2 separate
> areas containing data. Searching each of those individually
> (has_key()...) seems right to me.
If you need to search *both* data areas,
why not do it the obvious way, then?:
d = { "fred":"wilma", "barney":"betty" }
if "fred" in dict.keys(): # legal, and true
if "wilma" in dict.values(): # also legal, also true
logic: dictionaries do have a "has_key()" methods, but no "has_value()"
method
drawback: keys() and values() create copies of the dict's list of keys,
values,
so has_key() is much faster..
--
Patrick W. Bogaart
Department of Geomorphology and Quaternary Geology
Faculty of Earth Sciences, Vrije Universiteit Amsterdam
bogw at geo.vu.nl http://www.geo.vu.nl/users/bogw
More information about the Python-list
mailing list