一、字典特性介绍
字典在 Python 中极为重要,是属于映射类型的数据结构。 字典有⼀对⼉⼤括号组成 {} , 字典内的元素都是成对⼉出现的 {"a":1} , 他们⽤英⽂的冒号( : )隔开, 左边叫做键(key),右边的叫值(value), 通常叫做键值对⼉。 每个元素⽤英⽂的逗号 ( , ) 隔开{"a": 1, "b": 2}
二、创建字典
创建字典可以使⽤⼀对⼉⼤括号, 也可以使⽤ dict()
In [1]: d1 = {}
In [2]: type(d1)
Out[2]: dict
In [3]: d2 = dict()
In [4]: type(d2)
Out[4]: dict
三、字典的 key 和 value
1、字典的 key
在⼀个字典中,key 不允许有重复
In [5]: {"a":1,"a":10}
Out[5]: {'a': 10}
且必须是 python 中不可变的数据类型 如: 整型 浮点型 布尔值字符串 元组
In [6]: {1: "整型", 1.1: "浮点型", False: "布尔值", "abc":"字符串", (1,2): "
...: 元组" }
Out[6]: {1: '整型', 1.1: '浮点型', False: '布尔值', 'abc': '字符串', (1, 2): '元组'}
最常⽤的是字符串,因为⽐较容易有语意,易读
In [7]: {"user": "shark", "age": 18}
Out[7]: {'user': 'shark', 'age': 18}
扩展:python 中认为 1 和 True , 0 和 False 的值是相等的 但不是⼀个对象,因为它们的 id 不同
In [8]: {1: "整型", True: "布尔型"}
Out[8]: {1: '布尔型'}
In [9]: {True: "布尔型", 1: "整型"}
Out[9]: {True: '整型'}
2、字典中的 value
字典中的 value 可以是 Python 中任意的⼀个数据对象:整型、浮点型、布尔值、字符串、列表、元组、字典、函数对象等
In [10]: {'port': 3306, "height": 1.81, 'stat': True,"name": "dbserver"}
Out[10]: {'port': 3306, 'height': 1.81, 'stat': True, 'name': 'dbserver'}
In [11]: {"mysql-01": {
...: "cpu":4,
...: "memroy":[4066,4096]
...: }
...: }
Out[11]: {'mysql-01': {'cpu': 4, 'memroy': [4066, 4096]}}
函数对象
In [12]: def foo():
...: print("hello")
...:
In [13]: {"1":foo}
Out[13]: {'1': <function __main__.foo()>}
四、获取字典中 key 和 value
1、检查字典中是否存在某个 key
可以使⽤ in 关键字
In [14]: dic_map = {
...: "Manufacturer": "manufacturer",
...: "Product Name": "pod_name",
...: "Serial Number": "sn"
...: }
In [15]: dic_map
Out[15]:
{'Manufacturer': 'manufacturer',
'Product Name': 'pod_name',
'Serial Number': 'sn'}
In [16]: "Manufacturer" in dic_map
Out[16]: True
In [17]: "Manufactur" in dic_map
Out[17]: False
In [18]: line = '\tManufacturer: Alibaba Cloud'
In [19]: line.strip().split(': ')
Out[19]: ['Manufacturer', 'Alibaba Cloud']
In [20]: k = line.strip().split(': ')[0]
In [21]: k in dic_map
Out[21]: True
2、使⽤ [] 获取指定 key 的 value
In [22]: dic_map['Manufacturer']
Out[22]: 'manufacturer'
这种⽅式是⾮常的⾼效做法,推荐使⽤。 但是有个问题,假设获取字典中不存在的 key 的值
3、使⽤字典的 get() ⽅法
In [27]: dic_map.get('Manufacturer')
Out[27]: 'manufacturer'
In [28]: v = dic_map.get('Manufacturer')
In [29]: v
Out[29]: 'manufacturer'
In [30]: v = dic_map.get('Manufacturerr')
In [31]: v
In [32]: type(v) # key 不存在字典中,则返回 None
Out[32]: NoneType
In [33]: v = dic_map.get('Manufacturerr', 'key not in') # key 不存在,返回自定义值
In [34]: v
Out[34]: 'key not in'
4、循环字典的 key 和 value
字典对象的 items() ⽅法会获取到字典的 key 和 value, 它是⼀个可迭代对象
In [9]: for i in dic_map.items():
...: print(i)
...:
('Manufacturer', 'manufacturer')
('Product Name', 'pod_name')
('Serial Number', 'sn')
In [10]: for i in dic_map.items():
...: k, v = i
...: print(k , v)
...:
Manufacturer manufacturer
Product Name pod_name
Serial Number sn
5、向字典中添加键值对
方式一:[]
In [12]: info = {}
In [13]: info["cpu"] = 4
In [14]: info["memory"] = [4096,4096]
In [15]: info
Out[15]: {'cpu': 4, 'memory': [4096, 4096]}
字段映射
In [16]: dic_map
Out[16]:
{'Manufacturer': 'manufacturer',
'Product Name': 'pod_name',
'Serial Number': 'sn'}
In [17]: li = ['Manufacturer: Alibaba Cloud',
...: 'Product Name: Alibaba Cloud ECS',
...: 'Version: pc-i440fx-2.1',
...: 'Serial Number: 0f7e3d86-7742-4612-9f93-e3a9e4754157']
In [18]: prod_info = {}
In [19]: for line in li:
...: print(line)
...:
Manufacturer: Alibaba Cloud
Product Name: Alibaba Cloud ECS
Version: pc-i440fx-2.1
Serial Number: 0f7e3d86-7742-4612-9f93-e3a9e4754157
In [20]: for line in li:
...: print( line.split(': '))
...:
['Manufacturer', 'Alibaba Cloud']
['Product Name', 'Alibaba Cloud ECS']
['Version', 'pc-i440fx-2.1']
['Serial Number', '0f7e3d86-7742-4612-9f93-e3a9e4754157']
In [22]: for line in li:
...: k, v = line.split(': ')
...: if k in dic_map:
...: new_k = dic_map[k]
...: print(new_k,v)
...:
manufacturer Alibaba Cloud
pod_name Alibaba Cloud ECS
sn 0f7e3d86-7742-4612-9f93-e3a9e4754157
In [23]: for line in li:
...: k, v = line.split(': ')
...: if k in dic_map:
...: new_k = dic_map[k]
...: prod_info[new_k] = v # 获取的⼀个字典的值作为另⼀个字典的键
...:
In [24]: prod_info
Out[24]:
{'manufacturer': 'Alibaba Cloud',
'pod_name': 'Alibaba Cloud ECS',
'sn': '0f7e3d86-7742-4612-9f93-e3a9e4754157'}
方式二:update
In [25]: disk = {"disk": [10240]}
In [26]: info = {}
In [27]: info.update(disk)
In [28]: info
Out[28]: {'disk': [10240]}
In [29]: info.update({'cpu':4})
In [30]: info
Out[30]: {'disk': [10240], 'cpu': 4}
In [31]: info['disk']
Out[31]: [10240]
In [32]: info['disk'][0]
Out[32]: 10240
6、字典的编程之道:⽤字典实现 case 语句
In [45]: !vi some.py #程序
data = {
"0": "zero",
"1": "one",
"2": "two",
"q": "quit"
}
while True:
arg = input(">>:")
v = data.get(arg, "nothing")
if v == "quit":
break
print(v)
In [46]: %run some.py #执⾏程序
>>:1
one
>>:2
two
>>:3
nothing
>>:4
nothing
>>:q