请注意,根据文档:
dict.update
接受一个other
参数, “另一个字典对象或键/值对的可迭代” (我已经collections.Mapping
对此进行过测试)和 “如果指定了关键字参数,则使用这些键/值对更新字典” ;和dict()
需要一个Mapping
或一个Iterable
可选**kwargs
(与update
接受…相同)。
这不是您已经实现的接口,这会导致一些问题。我将实现如下:
from collections import Mappingclass DuplicateKeyError(KeyError): passclass UniqueKeyDict(dict): def __init__(self, other=None, **kwargs): super().__init__() self.update(other, **kwargs) def __setitem__(self, key, value): if key in self: msg = 'key {!r} already exists with value {!r}' raise DuplicateKeyError(msg.format(key, self[key])) super().__setitem__(key, value) def update(self, other=None, **kwargs): if other is not None: for k, v in other.items() if isinstance(other, Mapping) else other: self[k] = v for k, v in kwargs.items(): self[k] = v
正在使用:
>>> UniqueKeyDict((k, v) for k, v in ('a1', 'b2', 'c3', 'd4')){'c': '3', 'd': '4', 'a': '1', 'b': '2'}>>> UniqueKeyDict((k, v) for k, v in ('a1', 'b2', 'c3', 'a4'))Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> UniqueKeyDict((k, v) for k, v in ('a1', 'b2', 'c3', 'a4')) File "<pyshell#7>", line 5, in __init__ self.update(other, **kwargs) File "<pyshell#7>", line 15, in update self[k] = v File "<pyshell#7>", line 10, in __setitem__ raise DuplicateKeyError(msg.format(key, self[key]))DuplicateKeyError: "key 'a' already exists with value '1'"
和:
>>> ukd = UniqueKeyDict((k, v) for k, v in ('a1', 'b2', 'c3', 'd4'))>>> ukd.update((k, v) for k, v in ('e5', 'f6')) # single Iterable>>> ukd.update({'h': 8}, g='7') # single Mapping plus keyword args>>> ukd{'e': '5', 'f': '6', 'a': '1', 'd': '4', 'c': '3', 'h': 8, 'b': '2', 'g': '7'}
如果您最终使用过此功能,则我倾向于给它一个不同的名称
__repr__以避免混淆!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)