Home > Enterprise >  Initialize non existing keys in OrderedDict with default values like defaultDict
Initialize non existing keys in OrderedDict with default values like defaultDict

Time:12-30

Is there any way to access the non existing keys in OrderedDict with default values like which we do in defaultDict

Ex.
od = OrderedDict({'a':1})
print(od['b'])  # Output: KeyError: 'b'

This could work in defaultDict

Ex.
dd = defaultdict(int)
print(dd['b'])  # Output 0

CodePudding user response:

Just inherit from OrderedDict and redefine __getitem__:

from collections import OrderedDict


class OrderedDictFailFree(OrderedDict):
    def __getitem__(self, name):
        try:
            return OrderedDict.__getitem__(self, name)
        except KeyError:
            return None


od = OrderedDictFailFree({'a': 1})
print(od['b'])

CodePudding user response:

for example if you are looking for 0 as a default value for any non existed key. if keys are predefined then you can use setdefault()

from collections import defaultdict
od = defaultdict(lambda: 0, od )
  • Related