如何强制python中的字典拒绝现有键的更新? [英] How can I force a dictionary in python to reject updates of existing keys?
本文介绍了如何强制python中的字典拒绝现有键的更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以用Python设计字典,如果错误地添加了字典中已经存在的键,该字典将被拒绝吗?
谢谢
Is it possible to design a dictionary in Python in a way that if by mistake a key which is already in the dictionary is added, it gets rejected? thanks
推荐答案
您始终可以创建自己的字典
You can always create your own dictionary
class UniqueDict(dict):
def __setitem__(self, key, value):
if key not in self:
dict.__setitem__(self, key, value)
else:
raise KeyError("Key already exists")
这篇关于如何强制python中的字典拒绝现有键的更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文