【发布时间】:2015-11-22 09:16:48
【问题描述】:
假设我有d = {'dogs': 3}。使用:
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并为相关的魔术方法编写一个自定义函数。 -
你自相矛盾。你为什么不像你说的那样使用
d.update(dogs=1)? -
@chepner 嗯,我想我还不够清楚。因为该函数不打算创建新键,而是更改旧键的值。但是由于自动插入而忘记更改功能会被忽视。
-
不是您要求的,但如果键名由程序固定(不是从文件中读取),请考虑用自定义类替换您的字典。
__slots__声明修复了可以插入到此类对象中的属性名称。
标签: python dictionary key python-3.4