Python字典高级使用方法汇总
字典(dictionary)是python中的一种非常灵活和强大的数据结构,可以完成很多操作。本文总结了一些除了基本的初始化、赋值、取值之外的常用的字典使用方法。
使用dict创建字典的n种方法
除了我们比较常用的d = {'a':1, 'b':2}来初始化字典外,还可以使用dict()来初始化,这种方法更为灵活。以下介绍了用dict来初始化字典的几种方法。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<code class="hljs" coffeescript="">In [2]: dict?Type: typeString form: <type>Namespace: Python builtinDocstring:dict() -> new empty dictionarydict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairsdict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = vdict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)</type></code> |
参数赋值
|
1
2
3
4
|
<code class="hljs" objectivec="">In [6]: d = dict(a=1,b=2)In [7]: dOut[7]: {'a': 1, 'b': 2}</code> |
用可迭代对象为参数,且每一个迭代对象为(k, v)对
|
1
2
3
4
5
6
7
8
|
<code class="hljs" objectivec="">In [8]: l1 = ['a', 'b', 'c']In [9]: l2 = [1, 2, 3]In [11]: zip(l1,l2)Out[11]: [('a', 1), ('b', 2), ('c', 3)]In [12]: d = dict(zip(l1,l2))In [13]: dOut[13]: {'a': 1, 'b': 2, 'c': 3}</code> |
字典推导式(dictionary comprehension)
如同列表推导式,我们可以使用字典推导式来很简洁的生成一些字典。
|
1
2
3
4
|
<code class="hljs" javascript="">In [14]: d = { c:ord(c) for c in 'abc' }In [15]: dOut[15]: {'a': 97, 'b': 98, 'c': 99}</code> |
设置默认值
已经知道key的情况下批量生成默认值
如有一个列表l=['a', 'b', 'c'],要将其中的值作为key,值全部设为0。可以使用dict.fromkeys()来完成:
|
1
2
3
4
5
6
7
|
<code class="hljs" coffeescript="">In [16]: d.fromkeys?Type: builtin_function_or_methodString form: <built-in 0x10017b9c0="" at="" fromkeys="" method="" object="" of="" type="">Docstring:dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.v defaults to None.</built-in></code> |
示例代码:
|
1
2
3
4
5
|
<code class="hljs" objectivec="">In [17]: l = ['a','b','c']In [18]: d = {}In [19]: d.fromkeys(l, 0)Out[19]: {'a': 0, 'b': 0, 'c': 0}</code> |
若第二个参数不传入则默认为None。
事先不知道会有哪些key
如要对一段字符文本s = 'hello, world!'进行字符统计,将结果保存在字典中。
由于事先不知道会有哪些key,因此在一个新的值传入时,需要先判断该值是否在字典中,若存在,则加1,否则置为1。代码如下:
|
1
2
3
4
5
6
7
8
|
<code class="hljs" javascript="">d = {}s = 'hello, world!'for c in s: if c in d: d[c] += 1 else: d[c] = 1</code> |
使用defaultdict
defaultdict是collections中提供的设置了默认值的字典类型。
|
1
2
3
4
5
6
7
|
<code class="hljs" cs="">In [20]: from collections import defaultdictIn [21]: s = 'hello, world!'In [22]: d = defaultdict(int)In [23]: for c in s: d[c] += 1In [25]: dOut[25]: defaultdict(<type>, {'!': 1, ' ': 1, 'e': 1, 'd': 1, 'h': 1, 'l': 3, 'o': 2, ',': 1, 'r': 1, 'w': 1})</type></code> |
使用setdefault方法来实现同时设置默认值和取值
dict自带的setdefault方法,会在key存在时返回value,若不存在,则设为指定值并返回这个值。如:
|
1
2
3
4
5
6
7
8
|
<code class="hljs" objectivec="">In [29]: d = {'a':1, 'b':2}In [30]: d.setdefault('a', 3)Out[30]: 1In [31]: d.setdefault('c', 3)Out[31]: 3In [32]: dOut[32]: {'a': 1, 'b': 2, 'c': 3}</code> |
用这个方法实现上述功能为:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<code class="hljs" javascript="">In [26]: d2 = {}In [27]: for c in s: d2[c] = d2.setdefault(c, 0) + 1In [28]: d2Out[28]:{' ': 1, '!': 1, ',': 1, 'd': 1, 'e': 1, 'h': 1, 'l': 3, 'o': 2, 'r': 1, 'w': 1}</code> |
由此可见,在这种情况下,使用setdefault可以写出和使用defaultdict方法同样简洁的代码。
pop方法
python字典的pop方法会在键存在时返回该值,同时从字典中删除该键,若不存在可以返回默认值。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<code class="hljs" perl="">In [33]: dOut[33]: {'a': 1, 'b': 2, 'c': 3}In [34]: d.pop('a')Out[34]: 1In [35]: dOut[35]: {'b': 2, 'c': 3}In [36]: d.pop('d')---------------------------------------------------------------------------KeyError Traceback (most recent call last)<ipython-input-36-ee5e0ecd6e46> in <module>()----> 1 d.pop('d')KeyError: 'd'In [37]: d.pop('d', 0)Out[37]: 0</module></ipython-input-36-ee5e0ecd6e46></code> |
这个在我们需要判断一个特殊的字典并进行处理的时候非常有用。
假定我们有一个处理字典的函数:
|
1
2
3
|
<code class="hljs" python="">def process_dict(d): dosomething(d)</code> |
它接收所有人的字典并进行处理。假定现在你传入的字典需要进行一些其他的特殊处理,如何让函数识别传入的是你的字典并且不产生副作用呢?
我们可以将函数改为:
|
1
2
3
4
5
|
<code class="hljs" python="">def process_dict(d): if d.pop('is_mine', False): do_something_special(d) dosomething(d)</code> |
然后对于你要传入的字典设定k['is_mine']=True再传入该函数,进入函数后pop方法会将其弹出,识别出这是你的,进行一些操作,再继续。对于不存在该key的字典来说,返回False,不产生任何副作用。
遍历字典的n种方法
d.keys(),d.values(),d.items()分别返回键,值,键值对的列表。123456789<codeclass="hljs"perl=""> In [38]: dOut[38]: {'b':2,'c':3}In [39]: d.keys()Out[39]: ['c','b']In [40]: d.values()Out[40]: [3,2]In [41]: d.items()Out[41]: [('c',3), ('b',2)]</code>-
d.iterkeys(),d.itervalues(),d.iteritems()分别返回键,值,键值对的迭代对象。如果你只是想要遍历的话,建议使用这个。因为它不是一次生成所有对象,而是用一个生成一个,无论在速度还是内存占用上都有优势。123456<codeclass="hljs"css=""> In [42]: d.iterkeys()Out[42]: <dictionary-keyiterator0x103858578=""at="">In [43]: list(d.iterkeys())Out[43]: ['c','b']</dictionary-keyiterator></code> d.viewkeys(),d.viewvalues(),d.viewitems()返回一个类似set的对象,其特点是会随着d的变化而动态变化。1234567891011<codeclass="hljs"perl="">In [48]: dOut[48]: {'a':1,'b':2,'c':3}In [49]: keys = d.keys()In [50]: viewkeys = d.viewkeys()In [52]: del d['a']In [53]: dOut[53]: {'b':2,'c':3}In [54]: keysOut[54]: ['a','c','b']In [55]: viewkeysOut[55]: dict_keys(['c','b'])</code>

浙公网安备 33010602011771号