Generic dictionary
Thorsten Kampe
thorsten at thorstenkampe.de
Sun Nov 20 04:27:11 EST 2016
[Crossposted to tutor and general mailing list]
Hi,
I'd like to extend the dictionary class by creating a class that acts
like a dictionary if the class is instantiated with a dictionary and
acts like a "dictitem" ([(key1, value1), (key2, value2), ...]) if
instantiated with a list (that is dictitem).
The code (see extract at bottom) works well but it contains a lot of
"if this is a dictionary then do as a dictionary already does"
boilerplate code". How can I "inherit"(?)/"subclass"(?)/derive from
dict so I don't have to write the code for the dictionary case?
Thorsten
```
class GenericDict:
"""
a GenericDict is a dictionary or a list of tuples (when the keys
are not hashable)
"""
def __init__(inst, generic_dict):
inst._generic = generic_dict
def __getitem__(inst, key):
if isinstance(inst._generic, dict):
return inst._generic[key]
else:
return inst.values()[inst.keys().index(key)]
def values(inst):
if isinstance(inst._generic, dict):
return inst._generic.values()
else:
try:
return list(zip(*inst._generic))[1]
except IndexError: # empty GenericDict
return ()
def keys(inst):
if isinstance(inst._generic, dict):
return inst._generic.keys()
else:
try:
return list(zip(*inst._generic))[0]
except IndexError: # empty GenericDict
return ()
```
More information about the Python-list
mailing list