一.字典的定义
在python中,字典数据类型使用{}来定义,在大括号中,存储的是键值对,即key:value的形式,并且key不能有重复值,如果有重复,后面的值会覆盖前面的;值可以重复
# 字典的定义 dict1 = {"name": "xiaoming", "age":18, "sex": "man"} print(dict1) 结果: {'name': 'xiaoming', 'age': 18, 'sex': 'man'}View Code
二.字典的遍历
字典是无序的,所以不能像字符串,列表一样使用下标来遍历访问,那如何获取字典中的元素呢?
dict1 = {"name": "xiaoming", "age": 20, "sex": "man"} # print(dict1.keys()) # .keys()获取所有的键 for key in dict1.keys(): print(key) 结果如下 name age sex
dict1 = {"name": "xiaoming", "age": 20, "sex": "man"} # print(dict1.values()) # .values()获取所有的值 for value in dict1.values(): print(value) 结果如下 xiaoming 20 man
dict1 = {"name": "xiaoming", "age": 20, "sex": "man"} # print(dict1.items()) # .items()获取所有的键值对 for i in dict1.items(): print(i[0], i[1]) 结果如下 name xiaoming age 20 sex man
三.字典的常见操作
dict1 ={ "name": "xiaoming", "age": 19, "sex": "man" } print("字典类型和长度".center(30, "=")) print(len(dict1)) print(type(dict1)) # dict的常见操作 # 添加成员,直接赋值新的成员 print("添加成员".center(30, "=")) dict1["phonenumber"] = "1234567890" print(dict1) # 删除成员 print("删除成员".center(30, "=")) del dict1["phonenumber"] print(dict1) dict1.pop("sex") print(dict1) # 查询成员 # 通过键找值 print("查询成员".center(30, "=")) value = dict1.get("name") print(value) list1 = dict1.keys() list2 = dict1.values() print(list1) print(list2) # 修改 print("修改成员".center(30, "=")) dict1["name"] = "xianowang" print(dict1) 结果如下 ===========字典类型和长度============ 3 <class 'dict'> =============添加成员============= {'name': 'xiaoming', 'age': 19, 'sex': 'man', 'phonenumber': '1234567890'} =============删除成员============= {'name': 'xiaoming', 'age': 19, 'sex': 'man'} {'name': 'xiaoming', 'age': 19} =============查询成员============= xiaoming dict_keys(['name', 'age']) dict_values(['xiaoming', 19]) =============修改成员============= {'name': 'xianowang', 'age': 19}