Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 Dictionary in Operator

Python3 Dictionary in Operator

Python3 Dictionaries Python3 Dictionary


Description

The Python dictionary in operator checks whether a key exists in the dictionary; it returns true if the key is in dict, otherwise false.

The not in operator does the opposite: it returns false if the key is in dict, otherwise true.

Syntax

in operator syntax:


key in dict

Parameters

Return Value

Returns true if the key is in the dictionary, otherwise false.

Example

The following example shows how to use the in operator with dictionaries:

Example (Python 3.0+)

#!/usr/bin/python3

thisdict

= {

'

Name

'

:

'

Runoob

'

,

'

Age

'

:

7

}

Check whether key Age exists

if

'

Age

'

in

thisdict

:

print

(

"

Key Age exists

"

)

else

:

print

(

"

Key Age does not exist

"

)

Check whether key Sex exists

if

'

Sex

'

in

thisdict

:

print

(

"

Key Sex exists

"

)

else

:

print

(

"

Key Sex does not exist

"

)

not in

Check whether key Age does not exist

if

'

Age

'

not

in

thisdict

:

print

(

"

Key Age does not exist

"

)

else

:

print

(

"

Key Age exists

"

)

The output of the above example is:


键 Age 存在
键 Sex 不存在
键 Age 存在

Python3 Dictionaries Python3 Dictionary