Jef*_*ham 1 python dictionary idioms
目前,我正在尝试用Python填充字典,但我认为我所做的有点多余.是否有更多pythonic方式来执行以下操作:
if not pattern_file_map.get(which_match):
pattern_file_map[which_match] = [line]
else:
pattern_file_map[which_match].append(line)
Run Code Online (Sandbox Code Playgroud)
哪里pattern_file_map
是字典.
我知道在检查字典中是否有密钥时会有一定的习惯用法,比如 这个问题,但是我只想用一个列表来填充这个字典.
Sve*_*ach 10
你可以用
pattern_file_map.setdefault(which_match, []).append(line)
Run Code Online (Sandbox Code Playgroud)
代替.
其他人可能会建议使用collections.defaultdict(list)
替代,这是另一种选择,但要注意这可能会隐藏错误,因为它会静默创建您访问的所有密钥.