字典
❤ 创建使用花括号{};修改和添加元素的方法:字典名[字典的键]=值;删除元素:del 字典名[字典的键]
基础操作
※ 键在字典中是唯一的,但不同键却可以拥有相同的值,像列表这样的可变数据,不能用来当作字典的键
※ 通过字典变量[键]=某个值来对字典的某个数据项进行赋值。当该键已存在时,就修改该键对应的值;否则就创建一个键,并进行赋值。
score_dict = {"张三": 90, "李四": 85, "王五": 92, "李雷": 100, "韩梅梅": 100}
#访问
print(score_dict['李雷'])
#修改数据
score_dict["王五"] = 96
print(score_dict)
#新增数据
score_dict["Tom"] = 70
print(score_dict)
#删除数据
del score_dict["王五"]
print(score_dict)
#遍历
for key in score_dict.keys():
print("键是:{}" .format(key))
for value in score_dict.values():
print("值是:{}" .format(value))
for key, value in score_dict.items():
print("键是:{}, 值是:{}" .format(key, value))
输出结果如下:
100
{'张三': 90, '李四': 85, '王五': 96, '李雷': 100, '韩梅梅': 100}
{'张三': 90, '李四': 85, '王五': 96, '李雷': 100, '韩梅梅': 100, 'Tom': 70}
{'张三': 90, '李四': 85, '李雷': 100, '韩梅梅': 100, 'Tom': 70}
键是:张三
键是:李四
键是:李雷
键是:韩梅梅
键是:Tom
值是:90
值是:85
值是:100
值是:100
值是:70
键是:张三, 值是:90
键是:李四, 值是:85
键是:李雷, 值是:100
键是:韩梅梅, 值是:100
键是:Tom, 值是:70
字典嵌套
字典中存放列表:
例子一
pizza = {'crust':'thick','toppings':['potato','mushroom','extra cheese']}
#输出可以相加
print('you ordered a '+ pizza['crust']+'-crust pizza'+' '+'with the following topping:')
#遍历topping列表的值
for topping in pizza['toppings']:
print(topping)
#打印topping的第一个元素
print('配料表的第一个元素是:{}'.format(pizza['toppings'][0]))
#列表topping中加入'onion'
pizza['toppings'].append('onion')
print(pizza)
输出结果如下:
you ordered a thick-crust pizza with the following topping:
potato
mushroom
extra cheese
配料表的第一个元素是:potato
{'crust': 'thick', 'toppings': ['potato', 'mushroom', 'extra cheese', 'onion']}
例子二
pizza1 = {'crust':'thick','toppings':['mushroom','extra cheese']}
pizza2 = {'crust':'thin','toppings':['potato','onion']}
pizza3 = {'crust':'thick'}
#请补充代码,合并pizza1和pizza2的配料,作为pizza3的配料
piz=pizza1['toppings']+pizza2['toppings']
pizza3['toppings']=piz
print(pizza3)
输出结果如下:
{'crust': 'thick', 'toppings': ['mushroom', 'extra cheese', 'potato', 'onion']}
例子三
#班级分配练习
class_list = ["一班", "二班", "三班", "四班", "五班"]
class_student = {} # 创建一个空字典
#下面用变量c来对class_lsit进行遍历,设置每个键值对的值为空列表
for c in class_list:
class_student[c] = []
print("最初的班级字典是:{}" .format(class_student))
#添加班级人员信息
while True:
your_class = input("请输入你的班级:")
if your_class=='q':
break
elif your_class not in class_student:
print("输入班级错误")
else:
your_name = input("请输入你的姓名:")
print("**************************************")
class_student[your_class].append(your_name)
print(class_student)
print("三班的名单是:{},一班的名单是:{}".format(class_student['三班'],class_student['一班'][1]))
输出结果如下:
最初的班级字典是:{'一班': [], '二班': [], '三班': [], '四班': [], '五班': []}
请输入你的班级:一班
请输入你的姓名:姐姐
**************************************
请输入你的班级:二班
请输入你的姓名:谁谁谁
**************************************
请输入你的班级:三班
请输入你的姓名:儿童
**************************************
请输入你的班级:四班
请输入你的姓名:实施
**************************************
请输入你的班级:五班
请输入你的姓名:是是是
**************************************
请输入你的班级:六班
输入班级错误
请输入你的班级:一班
请输入你的姓名:lll
**************************************
请输入你的班级:
输入班级错误
请输入你的班级:三班
请输入你的姓名:试试
**************************************
请输入你的班级:一班
请输入你的姓名:33
**************************************
请输入你的班级:q
{'一班': ['姐姐', 'lll', '33'], '二班': ['谁谁谁'], '三班': ['儿童', '试试'], '四班': ['实施'], '五班': ['是是是']}
三班的名单是:['儿童', '试试'],一班的名单是:lll
列表中存放字典:
例子一
dict1 = {'姓名':'张三','专业':'美术','学号':'001'}
dict2 = {'姓名':'李四','专业':'计算机','学号':'002'}
dict3 = {'姓名':'王五','专业':'广告','学号':'003'}
student_info = [dict1,dict2,dict3]
#打印列表中前两个元素
print(student_info[:-1])
student_info[0]['学号']='004'
print(student_info)
输出结果如下:
[{'姓名': '张三', '专业': '美术', '学号': '001'}, {'姓名': '李四', '专业': '计算机', '学号': '002'}]
[{'姓名': '张三', '专业': '美术', '学号': '004'}, {'姓名': '李四', '专业': '计算机', '学号': '002'}, {'姓名': '王五', '专业': '广告', '学号': '003'}]
实践
用户名和密码两个列表,转换成一个字典输出:
users = ['xiaoxiangjun', 'lilei', 'hanmeimei', 'xiaoming']
passwords = ['123', '456', 'abc', 'qwe']
duiyingzhi={}
# 键值对组合,存放在集合里面
for i in users:
index=users.index(i)
duiyingzhi[i] = passwords[index]
print(duiyingzhi)
输出结果如下:
{'xiaoxiangjun': '123', 'lilei': '456', 'hanmeimei': 'abc', 'xiaoming': 'qwe'}
实战二
# 创建一个空字典,用来保存学生的姓名和评级
student_score = {}
# while True表示循环会一直执行,直到程序执行了break,循环才会中止
while True:
# 输入姓名,保存在name变量中,name为字符串类型
name = input("请输入学生姓名(输入q退出):")
if name == "q":
break
#请补全代码
else:
chengji=int(input("请输入学生成绩:"))
if 0<=chengji<=100:
if chengji>=90:
fanhui="优秀"
elif chengji>=80:
fanhui="良好"
elif chengji>=60:
fanhui="合格"
else:
fanhui="不合格"
student_score[name]=fanhui
# student_score[name].append(fanhui)
else:
print("请输入100以内的分数")
print(student_score)
contact_book = {}
contact_book["张三"] = {"年龄": 18, "性别": "男", "电话": "13666666666"}
contact_book["李四"] = {"年龄": 22, "性别": "男", "电话": "13888888888"}
contact_book["韩梅梅"] = {"年龄": 18, "性别": "女", "电话": "13999999999"}
print(contact_book)
#请补全代码
name=input("输入姓名:")
if name in contact_book:
for xinxi in contact_book[name]:
print("{}的{}是{}".format(name,xinxi,contact_book[name][xinxi]))
else:
print("{}不在联络簿中".format(name))