Skip to main content
 首页 » 编程设计

python之在 Python 中填充字典的更惯用的方法

2025年05月04日10落叶

目前,我正在尝试用 Python 填充字典,但我认为我正在做的事情有点多余。是否有更 pythonic 的方式来执行以下操作:

if not pattern_file_map.get(which_match): 
    pattern_file_map[which_match] = [line] 
else: 
    pattern_file_map[which_match].append(line) 

其中 pattern_file_map 是字典。

我知道在检查字典中是否有键时可以使用某种成语,比如 this question , 但我只想用列表填充这本字典。

请您参考如下方法:

你可以使用

pattern_file_map.setdefault(which_match, []).append(line) 

相反。

其他人可能会建议改用 collections.defaultdict(list),这是另一种选择,但要注意这可能会隐藏错误,因为它会默默地创建您访问的所有键。