1 # 字典
2 """
3 字典简介:
4 我们上学的时候都用过字典,如果遇到不明白的字,只要知道其拼音首字母就能找到其准确位置,故而知道其含义~
5 如:“我”,先找到 w 再找到 o 就能找到 “我” 字
6 字典 = {'w':'o'} 这就是字典的格式,当然,组合很多不止这一种
7 """
8 """
9 格式:
10 在我们程序中,字典:
11 earth = {'sea':'big_west_ocean','area':50,'position':'earth'}
12 dict = {key:value}
13 字典和列表一样,也能够存储多个数据
14 字典找某个元素时,是根据key来获取元素
15 字典的每个元素由2部分组成,键:值,【例如:'area':50】
16 """
17 # 1.根据键访问值——[]
18 erth = {'sea':'big_west_ocean','area':50,'position':'earth'}
19 print(erth['sea']) # big_west_ocean
20
21 # print(erth['abc']) # 返回报错 如下 (如果键不存在就会报错)
22 """
23 Traceback (most recent call last):
24 File "F:/test/7字典.py", line 21, in <module>
25 print(erth['abc'])
26 KeyError: 'abc'
27 """
28
29 # 2.根据键访问值——.get()
30 erth = {'sea':'big_west_ocean','area':50,'position':'earth'}
31 print(erth.get("abc")) # None
32 print(erth.get("abc","参数不存在")) # 参数不存在
33 print(erth.get("sea")) # big_west_ocean
34
35 # 3.字典的常见操作
36 # 3.1 修改元素【字典的每个元素中的数据是可以修改的,只要通过key找到,即可修改】
37 erth['area'] = 100
38 print(erth) # {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}
39
40 # 3.2 添加元素
41 """
42 在上面说了,当访问不存在的元素时会报错
43 那么在我们使用:变量名['键'] = 数据时,这个“键”不存在字典中,那么会新增这个元素
44 """
45 erth["aaaa"] = "bbbb"
46 print(erth) # {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth', 'aaaa': 'bbbb'}
47
48 # 3.3 删除元素
49 """
50 对元素的删除操作,有两种方式
51 del: 删除指定元素,删除整个字典
52 clear():清空整个字典
53 """
54 # del 删除指定元素
55 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth', 'aaaa': 'bbbb'}
56 del erth['aaaa']
57 print(erth) # {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}
58
59 # del 删除字典
60 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}
61 del erth
62 # print(erth) # 此步骤不用运行就会报错,变量不存在
63
64 # clear 清空整个字典
65 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}
66 erth.clear()
67 print(erth) # 返回 {}
68
69 # 4 查看字典中,键值对的个数:len【列表中也是一样的】
70 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}
71 print(len(erth)) # 3
72
73 # 5.1 查看字典中所有的key: key() (取出字典中所有的key值,返回的是列表)
74 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}
75 print(erth.keys()) # dict_keys(['sea', 'area', 'position'])
76
77 # 5.2 查看字典中所有的 value: value() (取出字典中所有的value值,返回的是列表)
78 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}
79 print(erth.values()) # dict_values(['big_west_ocean', 100, 'earth'])
80
81 # 6 查看字典中的元素:items() (返回的是包含所有(键、值)元素的列表)(也可以说是字典转列表的方法)
82 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}
83 print(erth.items()) # dict_items([('sea', 'big_west_ocean'), ('area', 100), ('position', 'earth')])
84
85 # 7 判断某个键是否存在字典中 返回 True 或者 False
86 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}
87 print(erth.__contains__("sea")) # True
88 print(erth.__contains__("sea123")) # False