Python dictionary key() method “retrieves the value associated with a given key”. If the key is not found in the dictionary, it returns a default value that can be specified as an optional second argument. If no default value is provided, it returns None.
Syntax
dictionary.get(keyname, value)
Parameters
The keyname name parameter and the keyname of the item you want to return the value from are required.
The value parameter is Optional. It is the value to return if the specified key does not exist. Default value None.
Example 1
GoT = {
"khaleesi": "Daenerys Targaryen",
"jon": "Aegon Targaryen",
"littlefinger": "Petyr Baelish"
}
print(GoT.get("jon"))
Output
Let’s take a scenario where the key is not in the dictionary.
Example 2
GoT = {
"khaleesi": "Daenerys Targaryen",
"jon": "Aegon Targaryen",
"littlefinger": "Petyr Baelish"
}
print(GoT.get("kingslayer"))
Output
So, if the key is absent, it will return None.
The get() method returns:
- The value for the specified key if key is in the dictionary.
- It returns None if the key is not found and the value is not specified.
- It returns a value if a key is not found and the value is specified.
That’s it.