# 字典是一个无序的数据集合,输出顺序和定义并不一定一样 """ 字典用键值对存储数据,键值对之间使用,分隔。 键是索引且唯一,只能使用字符串、数字或元组 值是数据,可取任何数据类型 """ xiaoming = {"name": "小明", "age": 18, "gender" : True, "height" : 1.75, "weight" : 75.5} print(xiaoming) # 字典的增删改查 xiaoming_dict = {"name": "xiaoming"} # 1.取值(取值时,key不存在会报错) print(xiaoming_dict["name"]) # 2.增加/修改 # 如果key存在,会修改。不存在,会增加 xiaoming_dict["age"] = 18 print(xiaoming_dict) xiaoming_dict["name"] = "小小明" print(xiaoming_dict) # 3.删除 xiaoming_dict.pop("name") print(xiaoming_dict) # 字典统计、合并与清空 xiaohua_dict = {"name": "小华", "age": 20} print(len(xiaohua_dict)) # 统计键值对数量 temp_dict = {"height": 1.80, "age": 21} xiaohua_dict.update(temp_dict) # 如果被合并的字典包含已经存在的键值对,会覆盖原有的键值对 print(xiaohua_dict) xiaohua_dict.clear() # 调用clear方法,清空所有键值对 print(xiaohua_dict) # 字典的循环遍历 xiaoming_dict = {"name": "小明", "qq": "123456", "phone": "10086"} # 变量K是每一次循环中,获取到的键值对的key for k in xiaoming_dict: print("%s - %s" % (k, xiaoming_dict[k]))
运行结果:
{‘name’: ‘小明’, ‘age’: 18, ‘gender’: True, ‘height’: 1.75, ‘weight’: 75.5}
xiaoming
{‘name’: ‘xiaoming’, ‘age’: 18}
{‘name’: ‘小小明’, ‘age’: 18}
{‘age’: 18}
2
{‘name’: ‘小华’, ‘age’: 21, ‘height’: 1.8}
{}
name - 小明
qq - 123456
phone - 10086