简体   繁体   English

使用 defaultDict 等默认值初始化 OrderedDict 中不存在的键

[英]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有什么方法可以使用默认值访问 OrderedDict 中不存在的键,就像我们在 defaultDict 中所做的那样

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

This is the real problem KeyError is thrown in the following implementation这是在下面的实现中抛出KeyError的真正问题

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__ :只需从OrderedDict继承并重新定义__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.例如,如果您正在寻找 0 作为任何不存在的键的默认值。 if keys are predefined then you can use setdefault()如果键是预定义的,那么您可以使用 setdefault()

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

This is certainly doable, as Yevgeniy Kosmak's answer shows.正如Yevgeniy Kosmak 的回答所示,这当然是可行的。 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.但是,请记住,在 Python >=3.7(或者甚至 >=3.6,只要您使用默认的 CPython 实现)中,所有字典现在都保持插入顺序 So in the event that you don't need compatibility with older versions, there's usually no real need to use OrderedDict at all.因此,如果您不需要与旧版本兼容,通常根本不需要使用 OrderedDict。 You can simply use defaultdict, and it will always keep its keys in order.您可以简单地使用 defaultdict,它会始终保持其键的顺序。

It seems we could use od.setdefault('b',0) although it's not that elegant solution.看起来我们可以使用od.setdefault('b',0)虽然它不是那么优雅的解决方案。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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