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

Python3 Dictionary get() Method

Python3 Dictionary get() Method

Python3 Dictionaries Python3 Dictionary


Description

The Python dictionary get() function returns the value of the specified key.

Syntax

get() method syntax:


dict.get(key[, value]) 

Parameters

Return Value

Returns the value of the specified key; if the key is not in the dictionary, returns the default value, or if no default is specified, returns None。

Example

The following example shows how to use the get() function:

Example

#!/usr/bin/python

tinydict

=

{

'Name'

:

'Runoob'

,

'Age'

:

27

}

print

(

"Age : "

,

tinydict.

get

(

'Age'

)

)

Sex is not set and no default value is given, so None is printed

print

(

"Sex : "

,

tinydict.

get

(

'Sex'

)

)

 

Salary is not set, so the default value 0.0 is printed

print

(

'Salary: '

,

tinydict.

get

(

'Salary'

,

0.0

)

)

The output of the above example is:


Age : 27
Sex : None
Salary: 0.0

Differences between the get() method and dict[key] access

The get(key) method can return a default value when the key is not in the dictionary None or the configured default value.

When the key is not in the dictionary, dict[key] raises KeyError exception.

Example

runoob

=

{

}

print

(

'URL: '

,

runoob.

get

(

'url'

)

)

   

Returns None

URL:  

None

print

(

runoob

[

'url'

]

)

   

A KeyError is raised

Traceback

(

most recent call last

)

:

  File

""

,

line

1

,

in

<
module
KeyError

:

'url'

Usage with nested dictionaries

The get() method is used with nested dictionaries as follows:

Example

#!/usr/bin/python

tinydict

=

{

'RUNOOB'

:

{

'url'

:

'www.runoob.com'

}

}

res

=

tinydict.

get

(

'RUNOOB'

,

{

}

)

.

get

(

'url'

)

Output result

print

(

"RUNOOB url is: "

,

str

(

res

)

)

The output of the above example is:


RUNOOB url 为 :  www.runoob.com

Python3 Dictionaries Python3 Dictionary