python入门之字典运用
"""
字典 dict
定义:
1.由一系列键值对组成的可变映射容器。
2.映射:一对一的对应关系,且每天记录无序。
3.键必须唯一且不可变(字符串/数字/元组),值没有限制。
"""
# 1.创建 # 空 dict01 = {} dict01 = dict() # 默认值 dict01 = {"wj": 100, "zm": 80, "zr": 90} dict01 = dict([("a", "b"), ("c", "d")]) # 构建字典 print(dict01) # 2.查找元素 print(dict01["a"]) # 如果key不存在,查找时会显示错误 # 如果存在key if "qty" in dict01: print(dict01["qty"]) # 3.修改元素(之前存在key) dict01["a"] = "bb" print(dict01["a"]) # 4.添加(之前不存在key) dict01["e"] = "f" print(dict01) # 5.删除 print(dict01) del dict01["a"] print(dict01) # 6.遍历(获取字典中所有元素) # 遍历字典,得到key for key in dict01: print(key) print(dict01[key]) # 遍历字典,获取value for value in dict01.values(): print(value) # 遍历字典,获取键值对 key value(元组) for k, v in dict01.items(): print(k) print(v)
练习:
# 练习1: # 在控制台中循环录入商品信息(名称,单价) # 如果名称输入空字符,则停止录入 # 将所有信息逐行打印 list_student_info = {} while True: name = input("请输入商品名称:") if name == "": break price = int(input("请输入商品单价:")) list_student_info[name] = price for key, value in list_student_info.items(): print("%s商品单价是%d" % (key, value))
# 练习2: # 在控制台中循环录入学生信息(姓名,年龄,成绩,性别) # 如果名称输入空字符,则停止录入 # 将所有信息逐行打印 """ 字典内嵌列表: { "张无忌":[28, 100, "男"] } """ list_student_info = {} while True: name = input("请输入学生姓名:") if name == "": break age = int(input("请输入学生年龄:")) score = int(input("请输入学生成绩:")) sex = input("请输入学生性别:") list_student_info[name] = [age, score, sex] for name, list_info in list_student_info.items(): print("%s的年龄是%d, 成绩是%d, 性别是%s" % (name, list_info[0], list_info[1], list_info[2]))
""" 字典内嵌字典: { "张无忌":{"age":28, "score":100, "sex":"男" }, } """ list_student_info = {} while True: name = input("请输入学生姓名:") if name == "": break age = int(input("请输入学生年龄:")) score = int(input("请输入学生成绩:")) sex = input("请输入学生性别:") list_student_info[name] = {"age": age, "score": score, "sex": sex} for name, dict_info in list_student_info.items(): print("%s的年龄是%d, 成绩是%d, 性别是%s" % (name, dict_info["age"], dict_info["score"], dict_info["sex"]))
""" 列表内嵌字典: [ {"name":张无忌, "age":28, "score":100, "sex":"男"} ] """ list_student_info = [] while True: name = input("请输入学生姓名:") if name == "": break age = int(input("请输入学生年龄:")) score = int(input("请输入学生成绩:")) sex = input("请输入学生性别:") dict_info = {"name": name, "age": age, "score": score, "sex": sex} list_student_info.append(dict_info) for dict_info in list_student_info: print("%s的年龄是%d, 成绩是%d, 性别是%s" % (dict_info["name"], dict_info["age"], dict_info["score"], dict_info["sex"]))
# 获取第一个学生信息 dict_info = list_student_info[0] print("第一个录入的是:%s,年龄是%d, 成绩是%d, 性别是%s" % (dict_info["name"], dict_info["age"], dict_info["score"], dict_info["sex"]))
 
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号