AppDividend
Latest Code Tutorials

Python Dictionary Get Example | Dictionary Get() Method Tutorial

0

Python Dictionary Get Example | Dictionary Get() Method Tutorial is today’s topic. Python Dictionary get() method returns the value for the specified key if the key is in the dictionary. Python 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 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"))

The output is following.

 

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"))

The output is following.

 

Dictionary Get() Method Tutorial

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

The get() method returns:

  • The value for the specified key if the key is in the dictionary.
  • It returns None if the key is not found and value is not specified.
  • 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)

The output is following.

 

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], KeyError exception is raised.

See the following code.

# app.py

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

The output is following.

 

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.