創建密鑰假設我有d = {'dogs': 3}
。使用:如何防止通過d [key] = val
d['cats'] = 2
將創建密鑰'cats'
,並給它的價值2
。
如果我真的打算用新的密鑰和值更新字典,我會使用d.update(cats=2)
,因爲它感覺更明確。
擁有自動創建一個鍵的感覺容易出錯(尤其是在較大的程序),例如:
# I decide to make a change to my dict.
d = {'puppies': 4, 'big_dogs': 2}
# Lots and lots of code.
# ....
def change_my_dogs_to_maximum_room_capacity():
# But I forgot to change this as well and there is no error to inform me.
# Instead a bug was created.
d['dogs'] = 1
問:
有沒有一種方法來禁用自動創建一個關鍵的這不存在通過d[key] = value
,而是提出KeyError
?
一切應繼續工作,雖然:
d = new_dict() # Works
d = new_dict(hi=1) # Works
d.update(c=5, x=2) # Works
d.setdefault('9', 'something') # Works
d['a_new_key'] = 1 # Raises KeyError
我想你可以繼承' dict'併爲相關的魔術方法編寫自定義函數。 – TigerhawkT3
看看這個http://stackoverflow.com/questions/2390827/how-to-properly-subclass-dict-and-override-getitem-setitem – ballsatballsdotballs
你已經自相矛盾。你爲什麼不用'd.update(狗= 1)'就像你說的那樣? – chepner