1.用字典的方式实现三级菜单,输入上级,显示下级列表,按b退出,按q返回上一级
data={ ‘北京‘:{ "昌平":{ "沙河":["oldbody","test"], "天通苑":["链家地产","我爱我家"], }, "朝阳":{ "望京":["奔驰","陌陌"], "国贸":["CICC","HP"], "东直门":["Advent","飞信"], }, "海淀":{}, }, ‘山东‘:{ "德州":{}, "青岛":{}, "济南":{} }, ‘广东‘:{ "东莞":{}, "常熟":{}, "佛山":{}, }, } exit_flag=False while not exit_flag: for i in data: print(i) choice=input("选择进入>>:") if choice in data: while not exit_flag: for i2 in data[choice]: print("\t",i2) choice2 = input("选择进入2>>:") if choice2 in data[choice]: while not exit_flag: for i3 in data[choice][choice2]: print("\t\t", i3) choice3 = input("选择进入3>>:") if choice3 in data[choice][choice2]: for i4 in data[choice][choice2][choice3]: print("\t\t",i4) choice4=input("最后一层,按b返回:") if choice4=="b": pass#相当于什么也不做,让代码不出错,占位符 elif choice4=="q": exit_flag=True if choice3 == "b": break elif choice3 == "q": exit_flag = True if choice2 == "b": break elif choice2 == "q": exit_flag = True
2.#key-vakue字典,字典是无序的,没有下标,只需要通过key来找,key尽量不要写中文
(1)
info={
‘stu1101‘:"TengLan Wu",
‘stu1102‘:"LongZe Luola",
‘stu1103‘:"XiaoZe Maliya",
}
b={
‘stu1101‘:"Alex",
1:3,
2:5,
}
‘‘‘
info.update(b)#把两个字典合并,有重复的合并,没有的创建
print(info)#{‘stu1101‘: ‘Alex‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1102‘: ‘LongZe Luola‘, 2: 5, 1: 3}
(2)
print(info.items())#把字典转换成了列表,输出dict_items([(‘stu1101‘, ‘Alex‘), (‘stu1103‘, ‘XiaoZe Maliya‘), (‘stu1102‘, ‘LongZe Luola‘), (2, 5), (1, 3)])
c=info.fromkeys([6,7,8])
print(c)#{8: None, 6: None, 7: None}创建了一个列表,有key,值为空
d=dict.fromkeys([6,7,8],"test")#{8: ‘test‘, 6: ‘test‘, 7: ‘test‘}初始化
print(d)
e=dict.fromkeys([6,7,8],[1,{"name":"alex"},444])#把后边的[1,{"name":"alex"},444都赋值给了6,7,8三个是一个地址
e[7][1]["name"]="Jack Chen"#{8: [1, {‘name‘: ‘Jack Chen‘}, 444], 6: [1, {‘name‘: ‘Jack Chen‘}, 444], 7: [1, {‘name‘: ‘Jack Chen‘}, 444]}
print(e)
3.字典的增删改查
# 查找
print(info["stu1101"])#TengLan Wu
# 修改
info["stu1101"]="武藤兰"
# 增加
info["stu1104"]="Cangjingkong"#有的话就修改,没有的话就直接创建一条数据
# 删除
del info["stu1101"]
info.pop("stu1101")#必须写
info.popitem()#随机删除数据
4.字典的查找和遍历
# 查找
# info[‘stu1104‘]#如果查找的时候不存在就会报错
print(info.get(‘stu1104‘))#返回值为None,这样的查找最安全,没有的话会返回None值而不会报错
print(‘stu1103‘ in info)#返回True,info.has_key("stu1103"),前边是python3中的,后边的是python2中的
# 遍历字典,建议使用的
for i in info:
print(i,info[i])
# 这个需要先把字典转换成列表,浪费时间,资源
for k,v in info.items():
print(k,v)