Created
December 30, 2009 03:20
-
-
Save mckoss/265815 to your computer and use it in GitHub Desktop.
DynDict - implement a nested collection of dictionaries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import UserDict | |
| class DynDict(UserDict.DictMixin): | |
| """ | |
| Implement a dynamic dictionary object, which acts as the union of the dictionaries | |
| from which it was created. | |
| The first dictionary is searched first, and subsequent dictionaries are searched when no results are found. | |
| New elements are always created in the first dictionary. | |
| """ | |
| def __init__(self, *args): | |
| self.dicts = args | |
| def __getitem__(self, key): | |
| for d in self.dicts: | |
| if key in d: | |
| return d[key] | |
| raise KeyError | |
| def __setitem__(self, key, value): | |
| self.dicts[0][key] = value | |
| def __delitem__(self, key): | |
| for d in self.dicts: | |
| if key in d: | |
| del d[key] | |
| def keys(self): | |
| s = set() | |
| for d in self.dicts: | |
| s.update(d.keys()) | |
| return list(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment