Python Dictionary get() Method

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

Python Dictionary Get Example

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

Dictionary Get() Method Tutorial

So, if the key is absent, it will return None.

The get() method returns:

  1. The value for the specified key if key is in the dictionary.
  2. It returns None if the key is not found and the value is not specified.
  3. It returns a value if a key is not found and the value is specified.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.