Книга: Practical Programming, Fourth Edition
Назад: Inverting a Dictionary
Дальше: Comparing Collections

Using the in Operator on Tuples, Sets, and Dictionaries

As with lists, the in operator can be applied to tuples and sets to check whether an item is a member of the collection:

​ ​>>>​​ ​​odds​​ ​​=​​ ​​set([1,​​ ​​3,​​ ​​5,​​ ​​7,​​ ​​9])​
​ ​>>>​​ ​​9​​ ​​in​​ ​​odds​
​ True
​ ​>>>​​ ​​8​​ ​​in​​ ​​odds​
​ False
​ ​>>>​​ ​​'9'​​ ​​in​​ ​​odds​
​ False
​ ​>>>​​ ​​evens​​ ​​=​​ ​​(0,​​ ​​2,​​ ​​4,​​ ​​6,​​ ​​8)​
​ ​>>>​​ ​​4​​ ​​in​​ ​​evens​
​ True
​ ​>>>​​ ​​11​​ ​​in​​ ​​evens​
​ False

When used on a dictionary, in checks whether a value is a key in the dictionary:

​ ​>>>​​ ​​bird_to_observations​​ ​​=​​ ​​{​​'canada goose'​​:​​ ​​183,​​ ​​'long-tailed jaeger'​​:​​ ​​71,​
​ ​...​​ ​​'snow goose'​​:​​ ​​63,​​ ​​'northern fulmar'​​:​​ ​​1}​
​ ​>>>​​ ​​'snow goose'​​ ​​in​​ ​​bird_to_observations​
​ True
​ ​>>>​​ ​​183​​ ​​in​​ ​​bird_to_observations​
​ False

Note that the values in the dictionary are ignored; the in operator only checks the keys.

Назад: Inverting a Dictionary
Дальше: Comparing Collections