DEV Community

Burdier
Burdier

Posted on

Default Value of a Dictionary, Python Trick

When you need get a value from dicctionary is very easy, anybody know how do it, but i believe this solution is unknow from a new programer of python.

the most common way to get a value from dictionary:

computer_component = {"output":"monitor","input":"teclado","storage":"SSD"}
get_component = computer_component['output']
print(get_component)

the problem with that is when value not exists in dictionary:

computer_component = {"output":"monitor","input":"teclado","storage":"SSD"}
get_component = computer_component['internet']
print(get_component)

#output:
#Traceback (most recent call last):
#  File "main.py", line 2, in <module>
#    get_component = computer_component['internet']
#KeyError: 'internet'

Ok, you can validate if value exists:

computer_component = {"output":"monitor","input":"teclado","storage":"SSD"}

if "internet" in computer_component.keys():
  print(computer_component["internet"])
else:
  print("internet 404")

#output:
#internet 404

but the best way to get value from a dictionary is this:

computer_component = {"output":"monitor","input":"teclado","storage":"SSD"}

print(computer_component.get("output","404"))

#output
#monitor

#--in case when value not exists:
print(computer_component.get("internet","404"))
#output
#404

where the firt param is the value and the second is the value by default.

Forgive me, but my English is a little bad, I want to improve it.

Top comments (0)