diff options
author | Raymond Hettinger <python@rcn.com> | 2004-03-04 08:25:44 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2004-03-04 08:25:44 (GMT) |
commit | 31017aed36a5c5b0e4b16ca58bea09c9ce360134 (patch) | |
tree | 766d70bb4fbb6878a71c81fc3874515cfcbc8aa8 /Lib/UserDict.py | |
parent | 6c79a518e70ea8e45e3287573d99c648ae3cb21b (diff) | |
download | cpython-31017aed36a5c5b0e4b16ca58bea09c9ce360134.zip cpython-31017aed36a5c5b0e4b16ca58bea09c9ce360134.tar.gz cpython-31017aed36a5c5b0e4b16ca58bea09c9ce360134.tar.bz2 |
SF #904720: dict.update should take a 2-tuple sequence like dict.__init_
(Championed by Bob Ippolito.)
The update() method for mappings now accepts all the same argument forms
as the dict() constructor. This includes item lists and/or keyword
arguments.
Diffstat (limited to 'Lib/UserDict.py')
-rw-r--r-- | Lib/UserDict.py | 28 |
1 files changed, 17 insertions, 11 deletions
diff --git a/Lib/UserDict.py b/Lib/UserDict.py index 8141e7f..87cc6a3 100644 --- a/Lib/UserDict.py +++ b/Lib/UserDict.py @@ -4,8 +4,6 @@ class UserDict: def __init__(self, dict=None, **kwargs): self.data = {} if dict is not None: - if not hasattr(dict,'keys'): - dict = type({})(dict) # make mapping from a sequence self.update(dict) if len(kwargs): self.update(kwargs) @@ -39,14 +37,18 @@ class UserDict: def itervalues(self): return self.data.itervalues() def values(self): return self.data.values() def has_key(self, key): return self.data.has_key(key) - def update(self, dict): - if isinstance(dict, UserDict): + def update(self, dict=None, **kwargs): + if dict is None: + pass + elif isinstance(dict, UserDict): self.data.update(dict.data) - elif isinstance(dict, type(self.data)): + elif isinstance(dict, type({})) or not hasattr(dict, 'items'): self.data.update(dict) else: for k, v in dict.items(): self[k] = v + if len(kwargs): + self.data.update(kwargs) def get(self, key, failobj=None): if not self.has_key(key): return failobj @@ -136,17 +138,21 @@ class DictMixin: raise KeyError, 'container is empty' del self[k] return (k, v) - def update(self, other): + def update(self, other=None, **kwargs): # Make progressively weaker assumptions about "other" - if hasattr(other, 'iteritems'): # iteritems saves memory and lookups + if other is None: + pass + elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups for k, v in other.iteritems(): self[k] = v - elif hasattr(other, '__iter__'): # iter saves memory - for k in other: - self[k] = other[k] - else: + elif hasattr(other, 'keys'): for k in other.keys(): self[k] = other[k] + else: + for k, v in other: + self[k] = v + if kwargs: + self.update(kwargs) def get(self, key, default=None): try: return self[key] |