Currently, I’m trying to fill a dictionary in Python but I think what I’m doing is a little bit redundant. Is there a more pythonic way to do the following:
if not pattern_file_map.get(which_match):
pattern_file_map[which_match] = [line]
else:
pattern_file_map[which_match].append(line)
where pattern_file_map is a dictionary.
I know that there is a certain idiom to use when checking if there is a key in a dictionary, like
this question, but I I just want to fill this dictionary with a lists.
You could use
instead.
Other people might suggest using a
collections.defaultdict(list)instead, which is another option, but be warned that this might hide errors, since it will silently create all keys you access.