我使用嵌套的defaultdict来保持代码的整洁,减少冗余代码。
我正在编制一本字典,例如:
{"Store1": {"Product1": 1}, "Store2": {"Product1": 2, "Product2": 1}}我试图实现这个问题Nested dictionary with defaults的答案,这将引发例外情况:
AttributeError: 'int' object has no attribute 'items'from collections import defaultdict, Counter
d = defaultdict(lambda: defaultdict(lambda: Counter()))
d["Store1"]["Product1"] += 1
print(d)例如,我是否可以:
d["Store1"]["Product1"] += 1发布于 2021-12-06 21:06:06
当您使用以下内容时
d = defaultdict(lambda: defaultdict(lambda: Counter()))
d["Store1"]["Product1"] += 1然后,d["Store1"]将创建一个" type“defaultdict(lambda: Counter())的新元素,因此d["Store1"]["Product1"]将创建一个类型为Counter的新元素。因此,当您执行+= 1时,它尝试通过1来增强Counter对象。但是,由于这些类型不兼容,所以没有定义:
>>> c = Counter()
>>> c += 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/---/lib/python3.7/collections/__init__.py", line 832, in __iadd__
for elem, count in other.items():
AttributeError: 'int' object has no attribute 'items'正如您可以看到的,它假设右侧遵循Mapping协议,并尝试添加r.h.s。它自己也算。例如:
>>> c = Counter(a=1)
>>> c += Counter(a=2, b=3)
>>> c
Counter({'a': 3, 'b': 3})另一方面,当您使用defaultdict(lambda: defaultdict(int))时,d["Store1"]["Product1"]会创建一个新的int对象,这个对象可以由+= 1递增并写回dict。
发布于 2021-12-06 21:00:25
你需要写些这样的东西
from collections import defaultdict, Counter
d = defaultdict(lambda: defaultdict(lambda: Counter()))
d["A"]["B"]["Store1"] += 1
print(d)https://stackoverflow.com/questions/70251789
复制相似问题