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'.
collections.defaultdict.if key not in my_dict: my_dict[key] = "not availableinstead of checking the opposite andpassingdictobjects, the easiest being usingmy_dict.get(key, default_value)when you want to retreive the value of a key that may not be there