Python学习笔记(字典)

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
bad Code
### good ###
d = {'name': 'python'}
print(d.get('name','default'))
#>>>python
print(d.get('wrongname','default'))
#>>>default
good Code

[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']}
bad Code
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']}
good Code
data = [
    ("animal", "bear"),
    ("animal", "duck"),
    ("plant", "cactus"),
    ("vehicle", "speed boat"),
    ("vehicle", "school bus")
]
data = dict(data)
print(data)
#>>>{'animal': 'duck', 'plant': 'cactus', 'vehicle': 'school bus'}
error Code

[4] 字典推导式

自Python2.7以后的版本,列表推导式扩展到字典、集合推导式

keys = ['animal', 'plant', 'vehicle']
values = ['bear', 'cactus', 'speed boat']

d = {}
for key, value in zip(keys, values):
    d[key] = value
print(d)
# >>>{'animal': 'bear', 'plant': 'cactus', 'vehicle': 'speed boat'}

d = dict([(key, value) for key, value in zip(keys, values)])
print(d)
# >>>{'animal': 'bear', 'plant': 'cactus', 'vehicle': 'speed boat'}
bad Code
keys = ['animal', 'plant', 'vehicle']
values = ['bear', 'cactus', 'speed boat']

d = {key: value for key, value in zip(keys, values)}
print(d)
# >>>{'animal': 'bear', 'plant': 'cactus', 'vehicle': 'speed boat'}
good Code

[5] 用字典实现 switch ... case 语句

Python 中没有 switch ... case 语句,这个问题Python之父龟叔表示这个语法过去没有,现在没有,以后也不会有。因为Python简洁的语法完全可以用 if ... elif 实现。如果有太多的分支判断,还可以使用字典来代替。

if arg == 0:
return 'zero'
elif arg == 1:
return 'one'
elif arg == 2:
return "two"
else:
return "nothing"
good

data = {
0: "zero",
1: "one",
2: "two",
}
data.get(arg, "nothing")

[6] 使用 iteritems 迭代字典中的元素

python提供了几种方式迭代字典中的元素,第一种是使用 items 方法:

d = {
0: "zero",
1: "one",
2: "two",
}

for k, v in d.items():
print(k, v)
items 方法返回的是(key ,value)组成的列表对象,这种方式的弊端是迭代超大字典的时候,内存瞬间会扩大两倍,因为列表对象会一次性把所有元素加载到内存,更好的方式是使用 iteritems

for k, v in d.iteritems():
print(k, v)
iteritems 返回的是迭代器对象,迭代器对象具有惰性加载的特性,只有真正需要的时候才生成值,这种方式在迭代过程中不需要额外的内存来装载这些数据。注意 Python3 中,只有 items 方法了,它等价于 Python2 中的 iteritems,而 iteritems 这个方法名被移除了。

 

[7] 用 defaultdict 初始化字典对象

如果不希望 d[x] 在 x 不存在时报错,除了在获取元素时使用 get 方法之外,另外一种方式是用 collections 模块中的 defaultdict,在初始化字典的时候指定一个函数,其实 defaultdict 是 dict 的子类。

from collections import defaultdict

groups = defaultdict(list)
for (key, value) in data:
groups[key].append(value)
当 key 不存在于字典中时,list 函数将被调用并返回一个空列表赋值给 d[key],这样一来,你就不用担心调用 d[k] 会报错了。

[8] 用 fromkeys 将列表转换成字典

keys = {'a', 'e', 'i', 'o', 'u' }
value = []
d = dict.fromkeys(keys, value)
print(d)

>>>
{'i': [], 'u': [], 'e': [],
'a': [], 'o': []}

 

参考文档:

官方指导 https://docs.python.org/3/library/stdtypes.html#mapping-types-dict

关于高效使用Python字典的清单 https://foofish.net/how-to-python-dict.html

Python参考手册

posted @ 2018-02-07 22:13  凡心已炽  阅读(172)  评论(0编辑  收藏  举报