# 字典的定义 dict 字典 dict1 = {} dict2 = dict() print(dict1, type(dict1)) print(dict2, type(dict2)) # 大括号抱起 逗号分割 键值对之间 用冒号 # 1.没有顺序 无法通过下标进行查找 # 2.只能通过键进行查找 dict3 = {"name": "秦小天", "age": 20, "gender": "man"} print(dict3, type(dict3))
dict1 = {"name": "fan", "sge": 18} print(dict1, type(dict1)) # {'name': 'fan', 'sge': 18} <class 'dict'> # 添加一对键值对 dict1["gender"] = "man" print(dict1, type(dict1)) # {'name': 'fan', 'sge': 18, 'gender': 'man'} <class 'dict'> # 删除键值对 del del dict1["gender"] print(dict1, type(dict1)) # {'name': 'fan', 'sge': 18} <class 'dict'> # 清空键值对 .clear dict1.clear() print(dict1, type(dict1)) # {} <class 'dict'> # 查找 {键:值} .get() dict2 = {"name": "shun", "age": 25} print(dict2["name"]) # shun # print(dict2["hei"]) # 没有会报错 print(dict2.get("age")) # 25 print(dict2.get("hei")) # 查找没有的键会返回None print(dict2.get("hei", 1)) # 没找到会返回后面的值 # 查找所有键 dict3 = {"name": "shun shun", "age": 25, "height": 170} # 查找所有的键 组成列表 print(dict3.keys(), type(dict3.keys())) # dict_keys(['name', 'age', 'height']) <class 'dict_keys'> # 查找所有的值 组成列表 print(dict3.values(), type(dict3.values())) # dict_values(['shun shun', 25, 170]) <class 'dict_values'> # 查找键值对 组成列表 没对键值对都是元组 print(dict3.items(), type(dict3.items())) # dict_items([('name', 'shun shun'), ('age', 25), ('height', 170)]) <class 'dict_items'> print("========================================") # 字典的遍历 # 遍历键 for key in dict3.keys(): print(key) # name # age # height print("========================================") # 遍历值 for val in dict3.values(): print(val) # shun shun # 25 # 170 print("========================================") # 遍历字典的键和值 for k, v in dict3.items(): print(k, ":", v) # name : shun shun # age : 25 # height : 170