1

Given a dictionary I need to check if certain keys exists, if they do I need to get their value, if they don't, then I have to set a default value. I am currently using this code:

if 'key1' in my_dict:
    pass
else:
    my_dict['key1'] = 'Not Available'

if 'key2' in my_dict:
    pass
else:
    my_dict['key2'] = 'Not Available'

if 'key3' in my_dict:
    pass
else:
    my_dict['key3'] = 'Not Available'

if 'key4' in my_dict:
    pass
else:
    my_dict['key4'] = 'Not Available'

This is of course painful, I guess I could iterate over the entire dictionary keys and check if the keys of interest are present, and if not, then set them. So the question is, is there a better way to do this? By this I mean, go through a large dictionary, check for keys, if they are not present set them to 'Not Available'.

4
  • 1
    Consider collections.defaultdict. Commented Apr 28, 2022 at 21:52
  • 1
    Well, for starters, here you should use if key not in my_dict: my_dict[key] = "not available instead of checking the opposite and passing Commented Apr 28, 2022 at 21:58
  • 1
    But there are various ways to handle default values in dict objects, the easiest being using my_dict.get(key, default_value) when you want to retreive the value of a key that may not be there Commented Apr 28, 2022 at 21:59
  • Does this answer your question? setting the missing values of dictionary with default value python Commented Jul 31, 2023 at 16:40

2 Answers 2

6

You can use the setdefault method

my_dict = {"a":1,"b":2}

If a key exists, there is no change made to the existing value

my_dict.setdefault('a', 3)
print(my_dict) #{'a': 1, 'b': 2}

If it doesn't exist, the key-value pair is added

my_dict.setdefault('c', 3)
print(my_dict) #{'a': 1, 'b': 2, 'c': 3}

Looping through multiple keys :

my_dict = {"a":1,"b":2}
keys = ["a","c","d"]
for key in keys:
    my_dict.setdefault(key, "Not Available")

print(my_dict) #{'a': 1, 'b': 2, 'c': 'Not Available', 'd': 'Not Available'}
Sign up to request clarification or add additional context in comments.

Comments

4

You could use dict.get(key[, default]):

>>> d = {'key1': 'apple'}
>>> d['key1']
'apple'
>>> d.get('key2', 'Not Available')
'Not Available'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.