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

Python Dictionary get() method

Python Dictionary get() method

Python Dictionary Python 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, or a default value if the key is not in the dictionary None or the configured default value.

Example

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

Example

#!/usr/bin/python

-- coding: UTF-8 --

tinydict

=

{

'Name'

:

'Runoob'

,

'Age'

:

27

}

print

(

"Age : %s"

%  tinydict.

get

(

'Age'

)

)

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

print

(

"Sex : %s"

%  tinydict.

get

(

'Sex'

)

)

 

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

print

(

'Salary: %s'

% 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

-- coding: UTF-8 --

tinydict

=

{

'RUNOOB'

:

{

'url'

:

'www.runoob.com'

}

}

res

=

tinydict.

get

(

'RUNOOB'

,

{

}

)

.

get

(

'url'

)

Output result

print

(

"RUNOOB url is: %s"

%

str

(

res

)

)

<

p

The output of the above example is:

<

/p

<

pre

RUNOOB url is: www.

runoob

.

com

<

/pre

Python Dictionary Python Dictionary