AppDividend
Latest Code Tutorials

Python Dictionary Get Example | Python dict Get() Method

0

Python dictionary get() is an inbuilt function that returns the value for a specified key if the key is in the dictionary. The dictionary get() method returns the value for the given key if present in the dictionary. If not, then it will return None.

Python Dictionary Get Example

The syntax of the Python Dictionary get() is following.

dictionary.get(keyname, value)

The keyname name parameter is required and the keyname of the item you want to return the value from.

The value parameter is Optional. It is the value to return if the specified key does not exist. Default value None.

See the following example.

# app.py

GoT = {
  "khaleesi": "Daenerys Targaryen",
  "jon": "Aegon Targaryen",
  "littlefinger": "Petyr Baelish"
}

print(GoT.get("jon"))

See the output.

Python Dictionary Get Example

Let’s take a scenario, where the key is not present in the dictionary.

# app.py

GoT = {
  "khaleesi": "Daenerys Targaryen",
  "jon": "Aegon Targaryen",
  "littlefinger": "Petyr Baelish"
}
print(GoT.get("kingslayer"))

See the output.

Dictionary Get() Method Tutorial

So, if the key is not present then, it will return None.

The get() method returns:

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

Use dict.get(key) to assign the default values

When Python Dictionary get() is called, Python checks if a specified key exists in the dictionary.

If it does, then get() method returns the value of that key. If the key does not exist, then the get() returns the value specified in the second argument of get().

# app.py

dictA = {"author": "Krunal"}
data = ""
if "author" in dictA:
    data = dictA["author"]
print(data)

See the output.

Use dict.get(key[, default]) to assign default values

Python get() method Vs dict[key] to Access Items

The get() method returns the default value if the key is missing.

However, if a key is not found when you use dict[key], the KeyError exception is raised.

See the following code.

# app.py

GoT = {
  "khaleesi": "Daenerys Targaryen",
  "jon": "Aegon Targaryen",
  "littlefinger": "Petyr Baelish"
}
print(GoT['kingslayer'])

See the output.

Python get() method Vs dict[key] to Access Items

So, we get the KeyError that says that kingslayer does not exist.

Finally, Python Dictionary Get Example | Dictionary Get() Method Tutorial is over.

Leave A Reply

Your email address will not be published.

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