[Tutor] use of the newer dict types

Peter Otten __peter__ at web.de
Fri Jul 26 11:34:52 CEST 2013


Albert-Jan Roskam wrote:

> <snip>
>>In Python 2, the preferred way to iterate over values or key/value pairs
>>was to use an iterator, since that is more light-weight than a list:
>>
>>for value in mydict.itervalues(): ...
> 
> if I have d = {1: 2}, I can do membership testing in the following two
> ways --but which one is the preferred way?: if 1 in d:
> pass
> if d.has_key(1):
> pass
> I find "in" (__contains__) more readable, but maybe has_key has advantages
> (speed)?

"in" is faster (use timeit to verify) and your only option in Python 3. 
has_key() has been kept in Python 2 for backwards compatibility -- a long 
time ago (before 2.2, released in 2001) it was your only option.





More information about the Tutor mailing list