1、字典提供了key-value之间的映射,支持以下基本操作:
x = d[k] 通过键进行索引
d[k] = x 通过键进行赋值
del d[k] 通过键删除一项
k in d 检查某个键是否存在
len(d) 字典中的项数
2、创建空字典的方式
d = {}
d = dict()
3、高效使用字典清单
[1] 使用in检查key是否存在,避免使用has_key()方法,has_key()方法已在python3中移除
[2] 使用get(key,default)方法获取value,当key不存在时,d[k]方式访问value,会抛出KeyError异常,为了避免或处理异常,需要增添额外的代码,而使用get(key,default)方法,代码更加简洁优美
### bad ### d = {‘name‘: ‘python‘} def foo(key,default=‘default‘): if key in d: return d[key] else: return default print(foo(‘name‘)) #>>>python print(foo(‘wrongname‘)) #>>>default def foo(key,default=‘default‘): try: return d[key] except KeyError as e: return default print(foo(‘name‘)) #>>>python print(foo(‘wrongname‘)) #>>>default
### good ### d = {‘name‘: ‘python‘} print(d.get(‘name‘,‘default‘)) #>>>python print(d.get(‘wrongname‘,‘default‘)) #>>>default
[3] 使用setdefault(key,default)方法为不存在的key设置缺省值,当key存在,返回key对应的value,等同于d[k]或d.get(k),当key不存在,等同于d[k]=default,并返回default
在做分类统计时,希望把同一类型的数据归到字典中的某种类型中,如下,把相同类型的事物用列表的形式重新组装,得到新的字典
data = [
("animal", "bear"),
("animal", "duck"),
("plant", "cactus"),
("vehicle", "speed boat"),
("vehicle", "school bus")
]
转换成
data = {
‘plant‘: [‘cactus‘],
‘animal‘: [‘bear‘, ‘duck‘],
‘vehicle‘: [‘speed boat‘, ‘school bus‘]
}
data = [ ("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus") ] group = {} for (key, value) in data: a = [] group.get(key, a).append(value) if key not in group: group[key] = a print(group) #>>>{‘animal‘: [‘bear‘, ‘duck‘], ‘plant‘: [‘cactus‘], ‘vehicle‘: [‘speed boat‘, ‘school bus‘]} group = {} for (key, value) in data: if key not in group: group[key] = [value] else: group[key].append(value) print(group) #>>>{‘animal‘: [‘bear‘, ‘duck‘], ‘plant‘: [‘cactus‘], ‘vehicle‘: [‘speed boat‘, ‘school bus‘]}
data = [ ("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus") ] group = {} for (key, value) in data: group.setdefault(key, []).append(value) print(group) #>>>{‘animal‘: [‘bear‘, ‘duck‘], ‘plant‘: [‘cactus‘], ‘vehicle‘: [‘speed boat‘, ‘school bus‘]}
参考文档:
官方指导 https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
关于高效使用Python字典的清单 https://foofish.net/how-to-python-dict.html
Python参考手册