How to return None if Dictionary key is not available

0 votes
I need a way to get a dictionary value if its key exists, or simply return None, if it does not.

However, Python raises a KeyError exception if you search for a key that does not exist. I know that I can check for the key, but I am looking for something more explicit. Is there a way to just return None if the key does not exist?
Apr 30, 2020 in Python by kartik
• 37,520 points
9,898 views

1 answer to this question.

0 votes

Hello @kartik,

You can use dict.get()

value = d.get(key)

which will return None if key is not in d. You can also provide a different default value that will be returned instead of None:

value = d.get(key, "empty")

Thank You!!

answered Apr 30, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
0 answers

How to return None if Dictionary key is not available?

I need a way to get a ...READ MORE

Apr 13, 2020 in Python by kartik
• 37,520 points
504 views
0 votes
1 answer

How to print a message or the error if a file is not found?

To print the message that file is not ...READ MORE

answered Jan 2, 2019 in Python by Omkar
• 69,230 points
2,764 views
0 votes
1 answer
0 votes
1 answer

Raw_input method is not working in python3. How to use it?

raw_input is not supported anymore in python3. ...READ MORE

answered May 5, 2018 in Python by aayushi
• 750 points
3,310 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,364 views
0 votes
1 answer
0 votes
1 answer

How to install biopyhton if import is not recognised as a command by the system?

Hello, For install biopyhton with proper instruction you can ...READ MORE

answered Oct 12, 2020 in Python by Niroj
• 82,880 points
596 views
0 votes
1 answer

How to remove a key from a Python dictionary?

Hello, If you need to remove a lot ...READ MORE

answered Apr 15, 2020 in Python by Niroj
• 82,880 points
1,649 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP