[Tutor] use of the newer dict types
Albert-Jan Roskam
fomcl at yahoo.com
Fri Jul 26 22:22:29 CEST 2013
----- Original Message -----
> From: Alan Gauld <alan.gauld at btinternet.com>
> To: tutor at python.org
> Cc:
> Sent: Friday, July 26, 2013 1:12 PM
> Subject: Re: [Tutor] use of the newer dict types
>
> On 26/07/13 09:50, Albert-Jan Roskam wrote:
>
>> 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
>
>
> In addition to being more readable (and the fact it's the only way in
> v3) 'in' has another big advantage - it's polymorphic:
>
> holds_1 = []
> bigBox = [ {1:2,3:4}, ['a',2,;freddy',True], (1,2,3) ]
>
> for collection in bigBox:
> if 1 in collection:
> holds_1.append(collection)
>
> You can't do that using has_key(), the code has to test
> for dict type etc.
>
> So all in all 'in' is the way to go.
Hmm, I'm in (pun intended ;-). Those are three very good arguments. I'll have a look if my IDE (PyCharm) warns about the incompatibility with Python 3.x (t does so with several things, like u'). Thank you!
More information about the Tutor
mailing list