defaultdict
当字典中的key不存在时,返回不再是keyError,而是一个默认值,这个默认值是int, list,set, str等。也就是返回一个空值。
类型 | 返回值 |
---|---|
int | 0 |
str | ‘’ |
list | [] |
字典用函数作为值
items = {
'laptop': lambda x: x * 600,
'raspberry pi': lambda x: x * 5,
'arduino': lambda x: x * 50
}
quantity = 4
value of laptop = items['laptop'](quantity)
print(f'value of {quantity} laptops = ${value_of_laptop}')
有哪些好用的库
字典库easydict和addict
pip install easydict
pip install addict
基本使用
>>> from addict import Dict
>>> mapping = Dict()
>>> mapping.a.b.c.d.e = 2
>>> mapping
{'a': {'b': {'c': {'d': {'e': 2}}}}}
针对json
>>> from easydict import EasyDict as edict
>>> from simplejson import loads
>>> j = """{
"Buffer": 12,
"List1": [
{"type" : "point", "coordinates" : [100.1,54.9] },
{"type" : "point", "coordinates" : [109.4,65.1] },
{"type" : "point", "coordinates" : [115.2,80.2] },
{"type" : "point", "coordinates" : [150.9,97.8] }
]
}"""
>>> d = edict(loads(j))
>>> d.Buffer
12
>>> d.List1[0].coordinates[1]
54.9
优先推荐使用 addict
treelib