Python3 Dictionary get() Method

Python3 字典Python3 Dictionary


Description

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

Syntax

get() method syntax:

dict.get(key[, value]) 

Parameters

  • key -- The key to be searched for in the dictionary.
  • value -- Optional. If the value of the specified key does not exist, return this default value.

Return Value

Returns the value of the specified key. If the key is not in the dictionary, returns the default value; if no default value is specified, returnsNone。

Example

The following example demonstratesget()the usage of the function:

Example

#!/usr/bin/python

tinydict = {'Name': 'Example', 'Age': 27}

print ("Age : ", tinydict.get('Age'))

# Sex is not set, and no default value is set, output None
print ("Sex : ", tinydict.get('Sex'))  

# Salary is not set, output the default value 0.0
print ('Salary: ', tinydict.get('Salary', 0.0))

The output of the above example is:

Age : 27
Sex : None
Salary: 0.0

Difference between get() method and dict[key] access

get(key) The method can return a default value when the key is not in the dictionary,Noneor the set default value.

dict[key]When the key is not in the dictionary, it will triggerKeyErroran exception.

Example

>>> example = {}
>>> print('URL: ', example.get('url'))     # Returns None
URL:  None

>>> print(example['url'])     # Triggers KeyError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'url'
>>>

Using Nested Dictionaries

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

Example

#!/usr/bin/python

tinydict = {'EXAMPLE' : {'url' : 'www.example.com'}}

res = tinydict.get('EXAMPLE', {}).get('url')
# Output result
print("EXAMPLE url is: ", str(res))

The output of the above example is:

EXAMPLE url 为 :  www.example.com

Python3 字典Python3 Dictionary

Other Extensions