Python_字典方法
Posted shz-blog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python_字典方法相关的知识,希望对你有一定的参考价值。
1. 方法
2. 例子
(1)增加/修改
- D[key] = value
1 >>> D = {1: ‘a‘, 2: ‘b‘, 3: ‘c‘}
2 >>> D[4] = ‘d‘
3 >>> D[1] = ‘A‘
4 >>> D
5 {1: ‘A‘, 2: ‘b‘, 3: ‘c‘, 4: ‘d‘}
6 >>> D[5]
7 Traceback (most recent call last):
8 File "<pyshell#4>", line 1, in <module>
9 D[5]
10 KeyError: 5
使用D[key],当key不存在时,会报错,可使用get或setdefault或defaultdict来避免KeyError异常(get在后面“查找”的例子里)。
- setdefault和defaultdict
1 >>> D = {}
2 >>> D.setdefault(1, str)
3 <class ‘str‘>
4 >>> D
5 {1: <class ‘str‘>}
6 >>> D[1] = ‘a‘
7 >>> D
8 {1: ‘a‘}
defaultdict中的default_factory可以是str、list、set、int等,key不存在时对应返回的分别是‘ ‘、[ ]、set()、0。
1 >>> from collections import defaultdict
2 >>> D = defaultdict(list)
3 >>> D[1]
4 []
5 >>> D
6 defaultdict(<class ‘list‘>, {1: []})
7 >>> D[1].append(‘a‘)
8 >>> D
9 defaultdict(<class ‘list‘>, {1: [‘a‘]})
- setdefault和defaultdict用来计数的例子:
参考地址:https://baijiahao.baidu.com/s?id=1635571891580252489&wfr=spider&for=pc
1 >>> L = list(‘abbccc‘)
2 >>> L
3 [‘a‘, ‘b‘, ‘b‘, ‘c‘, ‘c‘, ‘c‘]
4
5 >>> d1 = {}
6 >>> for item in L:
7 d1[item] = d1.setdefault(item, 0) + 1
8
9 >>> d1
10 {‘a‘: 1, ‘b‘: 2, ‘c‘: 3}
11
12 >>> from collections import defaultdict
13 >>> d2 = defaultdict(int)
14 >>> for item in L:
15 d2[item] += 1
16
17 >>> d2
18 defaultdict(<class ‘int‘>, {‘a‘: 1, ‘b‘: 2, ‘c‘: 3})
- update
1 >>> D = {‘a‘: 1, ‘b‘: 2, ‘c‘: 3}
2 >>> D.update({‘a‘: 11, ‘d‘: 4})
3 >>> D
4 {‘a‘: 11, ‘b‘: 2, ‘c‘: 3, ‘d‘: 4}
5 >>> D.update([(‘b‘, 22), (‘e‘, 5)])
6 >>> D
7 {‘a‘: 11, ‘b‘: 22, ‘c‘: 3, ‘d‘: 4, ‘e‘: 5}
8 >>> D.update(zip([‘c‘, ‘f‘], [33, 6]))
9 >>> D
10 {‘a‘: 11, ‘b‘: 22, ‘c‘: 33, ‘d‘: 4, ‘e‘: 5, ‘f‘: 6}
11 >>> D.update(d=44, g=7)
12 >>> D
13 {‘a‘: 11, ‘b‘: 22, ‘c‘: 33, ‘d‘: 44, ‘e‘: 5, ‘f‘: 6, ‘g‘: 7}
(2)删除
1 >>> D = {1: ‘a‘, 2: ‘b‘, 3: ‘c‘}
2 >>> del D[1]
3 >>> D
4 {2: ‘b‘, 3: ‘c‘}
5 >>> D.pop(1, ‘None‘)
6 ‘None‘
7 >>> D.popitem()
8 (3, ‘c‘)
9 >>> D
10 {2: ‘b‘}
11 >>> D.clear()
12 >>> D
13 {}
14 >>> del D
15 >>> D
16 Traceback (most recent call last):
17 File "<pyshell#9>", line 1, in <module>
18 D
19 NameError: name ‘D‘ is not defined
(3)查找
1 >>> D = {1: ‘a‘, 2: ‘b‘, 3: ‘c‘}
2 >>> D.get(1, -1)
3 ‘a‘
4 >>> D.get(4, -1)
5 -1
6 >>> D.items()
7 dict_items([(1, ‘a‘), (2, ‘b‘), (3, ‘c‘)])
8 >>> D.keys()
9 dict_keys([1, 2, 3])
10 >>> D.values()
11 dict_values([‘a‘, ‘b‘, ‘c‘])
(4)浅拷贝
1 >>> d1 = {1: [‘a‘, ‘b‘], 2: ‘c‘}
2 >>> d2 = d1.copy()
3 >>> id(d1) == id(d2)
4 False
5 >>> id(d1[1]) == id(d2[1])
6 True
注:浅拷贝和深拷贝的区别,详情见https://www.cnblogs.com/shz-blog/p/12451730.html
以上是关于Python_字典方法的主要内容,如果未能解决你的问题,请参考以下文章