![](/img/trans.png)
[英]What's the most idiomatic way to implement a stack for `dictionary` type in `Python`?
[英]A more idiomatic way to fill a dictionary in Python
目前,我正在嘗試用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
是字典。
我知道檢查字典中是否有鍵時會使用某種習語,例如這個問題 ,但是II只是想用列表填充該字典。
你可以用
pattern_file_map.setdefault(which_match, []).append(line)
代替。
其他人可能建議改用collections.defaultdict(list)
,這是另一種選擇,但要警告這可能會隱藏錯誤,因為它將以靜默方式創建您訪問的所有鍵。
您可以嘗試使用collections.defaultdict 。
由於您要添加一個可能存在的值:
pattern_file_map.setdefault(which_match, []).append(line)
如果使用dict.get()
:
li = pattern_file_map.get(which_match, [])
li.append(line)
pattern_file_map[which_match] = li
當然,這兩種情況都限於dict的值為列表的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.