Python Dictionary get() method
Python Dictionary get() method
The dictionary.get() method returns the value of the item with the specified key.
Syntax
dictionary.get(keyname, value)
Parameter
keyname- This parameter represents the key to be searched in the dictionary.
value- The parameter represents a value to return if the specified key does not exist and its default value none.
Return
This method returns the value for the specified key if the key is in dictionary else it returns none if the key is not found and value is not specified.
Example 1
# the python program representing # the dictionary.get() method # initialising the dictionary fruits = { "banana": "apple", "orange": "mango", "grapes": 5 } # printing the Dictionary print("Dictionary:",fruits) # returning the value of the item with the specified key. priceFruit=fruits.get("price",9876) print("My price of fruite is Rs", priceFruit)
Output
Dictionary: {'banana': 'apple', 'grapes': 5, 'orange': 'mango'} My price of fruite is Rs 9876
Example 2
# the python program representing # the dictionary.get() method # initialising the dictionary person = {'name': 'Reema', 'language':'Python','age': 22} # will return the key value of name and language print('Name: ', person.get('name')) print('Language: ', person.get('language')) # when the value is not provided it returns none print('ID: ', person.get('id')) # value is provided print('id: ', person.get('id', 127890))
Output
Name: Reema Language: Python ID: None id: 127890