python - Python:默认字典初始化
问题描述
我创建了一个默认字典,如下所示:
from collections import defaultdict
dd = defaultdict(lambda : "Key not found")
dd = {'a':1,'b':2}
print(dd)
print(dd['a']) # Prints 1
print(dd['c']) # Throws KeyError
但是,下面的代码片段有效:
from collections import defaultdict
(lambda : "Key not found")
dd['a']=1
dd['b']=2
print(dd)
print(dd['a']) # Prints 1
print(dd['c']) # Prints "Key not found"
谁能解释一下为什么第一个代码片段会引发错误,而第二个代码片段可以按预期运行..
解决方案
你已经覆盖dd = defaultdict(lambda : "Key not found")
了,dd = {'a':1,'b':2}
所以它defaultdict()
变成了dict()
.
推荐阅读
- javascript - How to convert an array and an object to enable one-to-one correspondence?
- git - increment git version with travis when publishing a repo
- python - Python3.7: Metaclassing from Tuple base class, receiving Type error
- javascript - how to auto increment, if I type 2015 on text1, text2 should display 2016. is there an easy way to this?
- ios - Getting an error "Expected a MKTileOverlay but got (null)" when trying to add MKTileOverlay object to MKMapView
- javascript - Cannot set property 'products' of undefined in Vue.js
- javascript - 当首先没有初始状态时,如何从对象切换元素?
- python - 无法连接到 Docker 中的 Elasticsearch
- python - 在for循环中合并索引上的数据帧
- node.js - 代理不适用于快递。好像没有定义