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'.
CodePudding user response:
You could use dict.get(key[, default])
:
>>> d = {'key1': 'apple'}
>>> d['key1']
'apple'
>>> d.get('key2', 'Not Available')
'Not Available'
CodePudding user response:
You can use the set_default
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'}