Python Dictionary get()
The get() method returns the specified value of the given key if it's present in the dictionary.
Python Dictionary get()
The syntax of get() is:
1
2
dictionary.get(key, value)
get() Parameters
The get() method takes two parameters as argument :
- key - Name of the key you want to return the value from dictionary.
- value (Optional) - The value to be returned if the given key is not found in the dictionary .The default value if None.
Lets see some examples of get() method in python dictionaries?
Example 1: How to use get() in python dictionaries?
1
2
3
4
5
6
7
8
9
10
11
person = {'name': 'Coco', 'age': 6}
print('Name: ', person.get('name'))
print('Age: ', person.get('age'))
# value is not provided
print('Bread: ', person.get('bread'))
# value is provided
print('Bread: ', person.get('bread', 0.0))
Output:
1
2
3
4
5
Name: Coco
Age: 6
Bread: None
Bread: 0.0
This post is licensed under CC BY 4.0 by the author.