简体   繁体   中英

Initialize non existing keys in OrderedDict with default values like defaultDict

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 is the real problem KeyError is thrown in the following implementation

l =['a','b','c','b']
od = OrderedDict({})

for k in l:
    od[k] += 1 # KeyError

This implementation is intentionally avoided

for k in l:
    if k in od:
        od[k] += 1
    else:
        od[k] = 1

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

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 )

This is certainly doable, as Yevgeniy Kosmak's answer shows. However, keep in mind that in Python >=3.7 (or even >=3.6 as long as you're using the default CPython implementation), all dictionaries now maintain insertion order anyway. So in the event that you don't need compatibility with older versions, there's usually no real need to use OrderedDict at all. You can simply use defaultdict, and it will always keep its keys in order.

It seems we could use od.setdefault('b',0) although it's not that elegant solution.

od = OrderedDict({'a':1})
print(od.setdefault('b',0)) # od.get('b',0) could be used if intention is not to change od
l =['a','b','c','b','b']
od = OrderedDict({})

for k in l:   
    od[k] = od.setdefault(k,0) + 1 # set key to 0 if there in no key k and increment by 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM