标签:
Python 字典
字典的特点
1、字典由key、value组成
2、字典中的key的值是唯一的
3、字典种的key是无序的
4、字典中的key可以取任何数据类型,但是必须是不可变的
5、字典的值可以重复,并且可以改变
字典基本操作方法
1、赋值
|
1
2
3
4
5
6
7
8
9
|
>>> dict1 = {"one" : 1, "two" : 2}>>> dict2 = {}>>> dict2["three"] = 3>>> dict2["four"] = 4#如果之前没有定义这个变量为字典,那么直接用下面这种方式会报错>>> dict3["five"] = 5Traceback (most recent call last): File "<input>", line 1, in <module>NameError: name ‘dict3‘ is not defined |
2、增加
|
1
2
3
|
>>> dict1["name"] = "King">>> print (dict1){‘one‘: 1, ‘name‘: ‘King‘, ‘two‘: 2} |
3、修改
|
1
2
3
4
5
6
7
8
9
|
>>> dict1["name"] = "Tom">>> print (dict1){‘one‘: 1, ‘name‘: ‘Tom‘, ‘two‘: 2}>>> dict1["name"] = "Tom">>> dict2 = {"three":3, "name": "alex"}#update方法将dict2中存在dict1中不存在的键值加上,dict1中存在的键的值进行修改>>> dict1.update(dict2)>>> print (dict1){‘two‘: 2, ‘three‘: 3, ‘one‘: 1, ‘name‘: ‘alex‘} |
4、删除
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
>>> dict1 = {"a":1, "b":2, "c":3, "d":4, "e":5}#删除并返回值>>> dict1.pop("c")3>>> print (dict1){‘b‘: 2, ‘e‘: 5, ‘d‘: 4, ‘a‘: 1}#仅删除>>> del dict1["b"]>>> print (dict1){‘e‘: 5, ‘d‘: 4, ‘a‘: 1}#随机删除并返回值>>> dict1.popitem()(‘e‘, 5)>>> print (dict1){‘d‘: 4, ‘a‘: 1} |
5、查找
|
1
2
3
4
5
6
7
8
9
10
11
12
|
>>> dict1 = {"a":1, "b":2, "c":3, "d":4, "e":5}>>> dict1["a"]1>>> dict1.get("a")1#这种方法当key不存在时会报错>>> dict1["f"]Traceback (most recent call last): File "<input>", line 1, in <module>KeyError: ‘f‘#这种方法当key不存在时返回为空>>> dict1.get("f") |
6、key、value输出
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
>>> dict1 = {"a":1, "b":2, "c":3, "d":4, "e":5}#输出字典中所有的key>>> print (dict1.keys())dict_keys([‘b‘, ‘c‘, ‘e‘, ‘d‘, ‘a‘])#输出字典中所有的value>>> print (dict1.values())dict_values([2, 3, 5, 4, 1])#输出字典中的键值(不推荐,需要转换成列表,效率低)>>> for key,value in dict1.items():... print (key,value)... b 2c 3e 5d 4a 1#推荐做法>>> for key in dict1:... print (key,dict1[key])... b 2c 3e 5d 4a 1#排序输出>>> for key in sorted(dict1):... print (key,dict1[key])... a 1b 2c 3d 4e 5#输出索引和key、value>>> for index,key in enumerate(dict1):... print (index,key,dict1[key])... 0 b 21 c 32 e 53 d 44 a 1 |
7、其它操作
|
1
2
3
4
5
6
7
8
9
10
11
|
#不推荐用,有坑>>> dict.fromkeys([‘a‘,‘b‘,‘c‘],‘test‘){‘b‘: ‘test‘, ‘c‘: ‘test‘, ‘a‘: ‘test‘}#setdefault在字典中存在的键不做变动,没有的则添加>>> a = {‘a‘:1, ‘b‘:2, ‘c‘:3}>>> a.setdefault("c",4)3>>> a.setdefault("d",4)4>>> print (a){‘a‘: 1, ‘c‘: 3, ‘d‘: 4, ‘b‘: 2} |
标签:
原文地址:http://www.cnblogs.com/Kingway-Python/p/5815851.html