Obtener datos de diccionarios
Disclaimer: This post has been translated to English using a machine translation model. Please, let me know if you find any mistakes.
Let's imagine that we have the following dictionary
dictionary = {"id": 1,"name": "John","age": 30}
If we want to obtain the value of the age, what is usually done is dictionary["age"]
dictionary = {"id": 1,"name": "John","age": 30}dictionary["age"]
30
But, what happens if the key
we put in is not in the dictionary? Will it give us an error?
dictionary["country"]
---------------------------------------------------------------------------KeyError Traceback (most recent call last)Cell In[4], line 1----> 1 dictionary["country"]KeyError: 'country'
So if this happens in production, the program will crash
So to solve it we can use a try except
to handle the error
try:dictionary["country"]except KeyError:print("Key not found")
Key not found
But another solution to avoid filling the code with try except
is to use the get
method which allows us to obtain the value of a key
and if it doesn't exist, it returns a default value.
dictionary.get("country", "Key not found")
'Key not found'
Another option is not to include the second option, in which case we get None
if the key
does not exist.
country = dictionary.get("country")print(country)
None