DEV Community

Burdier
Burdier

Posted on

3 1

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay