Generic dictionary

Peter Otten __peter__ at web.de
Sun Nov 20 04:43:01 EST 2016


Thorsten Kampe wrote:

> [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?

Hm.

def GenericDict(dict_or_items):
    if isinstance(dict_or_items, dict):
        return dict(dict_or_items)
    else:
        return SimpleGenericDictWithOnlyTheFalseBranchesImplemented(
            dict_or_items
        )

> 
> 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)]

It's not obvious why you'd ever want that. What's the use case?
If you have unhashable keys consider bisect...
 
>     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