Python3 Att Dictionary Get
# Python3.x Python3 Dictionary get() Method
[ Python3 Dictionary](#)
* * *
## Description
The Python dictionary get() function returns the value for the specified key.
## Syntax
The get() method syntax:
dict.get(key[, value])
## Parameters
* key -- The key to look up in the dictionary.
* value -- Optional. The value to return if the specified key does not exist.
## Return Value
Returns the value for the specified key. If the key is not in the dictionary, returns the default value. If no default value is specified, returns **None**.
## Example
The following example demonstrates the usage of the get() function:
## Example
#!/usr/bin/python
tinydict ={'Name': 'Tutorial','Age': 27}
print("Age : ", tinydict.get('Age'))
# No Sex set, and no default value set, outputs None
print("Sex : ", tinydict.get('Sex'))
# No Salary set, outputs default value 0.0
print('Salary: ', tinydict.get('Salary',0.0))
The output of the above example is:
Age : 27Sex : NoneSalary: 0.0
### get() Method vs dict Access Difference
The get(key) method can return the default value **None** or a set default value when the key is not in the dictionary.
dict will raise a **KeyError** exception when the key is not in the dictionary.
## Example
>>> tutorial ={}
>>>print('URL: ', tutorial.get('url'))# Returns None
URL: None
>>>print(tutorial['url'])# Raises KeyError
Traceback (most recent call last):
File "", line 1,in
KeyError: 'url'
>>>
### Nested Dictionary Usage
The get() method's usage with nested dictionaries is as follows:
## Example
#!/usr/bin/python
tinydict ={'TUTORIAL' : {'url' : 'www.'}}
res = tinydict.get('TUTORIAL',{}).get('url')
# Output result
print("TUTORIAL url is : ",str(res))
The output of the above example is:
TUTORIAL url is : www.
* * Python3 Dictionary](#)
YouTip