Python Dictionary get() Method
Description
Python Dictionaryget()The function returns the value of the specified key.
Syntax
Syntax of get() method:
dict.get(key[, value])
Parameters
- key -- The key to look up in the dictionary.
- value -- Optional, if the value for 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 valueNoneor the set default value.
Example
The following example demonstratesget()how to use the function:
Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
tinydict = {'Name': 'Example', 'Age': 27}
print ("Age : %s" % tinydict.get('Age'))
# Sex is not set and no default value is set, outputs None
print ("Sex : %s" % tinydict.get('Sex'))
# Salary is not set, outputs the default value 0.0
print ('Salary: %s' % tinydict.get('Salary', 0.0))
# -*- coding: UTF-8 -*-
tinydict = {'Name': 'Example', 'Age': 27}
print ("Age : %s" % tinydict.get('Age'))
# Sex is not set and no default value is set, outputs None
print ("Sex : %s" % tinydict.get('Sex'))
# Salary is not set, outputs the default value 0.0
print ('Salary: %s' % tinydict.get('Salary', 0.0))
The output of the above example is:
Age : 27 Sex : None Salary: 0.0
get() Method vs dict[key] Access Element Difference
get(key) The get() method can return a default value when the key is not in the dictionaryNoneor the set default value.
dict[key]When the key is not in the dictionary, it triggersKeyErroran 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'
>>>
>>> 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 usage of the get() method for nested dictionaries is as follows:
Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
tinydict = {'EXAMPLE' : {'url' : 'www.example.com'}}
res = tinydict.get('EXAMPLE', {}).get('url')
# Output result
print("EXAMPLE url is : %s" % str(res))
<p>The output of the above example is:</p>
<pre>
EXAMPLE url is : www.example.com
</pre>
# -*- coding: UTF-8 -*-
tinydict = {'EXAMPLE' : {'url' : 'www.example.com'}}
res = tinydict.get('EXAMPLE', {}).get('url')
# Output result
print("EXAMPLE url is : %s" % str(res))
<p>The output of the above example is:</p>
<pre>
EXAMPLE url is : www.example.com
</pre>
Python Dictionary