字典
info={
'stu01':'zhangsan',
'stu02':'lisi',
'stu03':'wangwu',
}
#字典储存时是无序的,只能通过key来搜索
字典更改
info['stu01']='张三'
b = {'stu02':'hodang',1:2,2:3}
info.update(b) #两个字典合并,key重合则覆盖
c = info.fromkeys([6,7,8],'first') #创建字典c,key为6,7,8,值为first,否则为none
字典删除
del info['stu03']
info.pop('stu02') #不写默认删除最后一个(无序的最后一个)
info.popitem() #随机删除
字典查找
info['stu01'] #字典必须有此key,否则一般不用此方法
print(info.get('stu01')) #有则输出,无则为null。安全取值的方法
print('stu01' in info) #判断该值是否在此字典中
字典循环
for i in info:
print(i,info[i]) #i代指key
for k,v in info.items():
print(k,v) #不如第一种高效
多级嵌套字典
catalog = {
'学生':{
'stu1':['01',123],
'stu2':['02',124],
},
'老师':{
'tea1':['01',123],
'tea2':['02',124],
},
}
catalog['学生']['stu1'][0] = '03'
catalog.setdefault('管理员',{['01',123]}) #如果能取到 '管理员',则输出,否则创建新字典项 '管理员'
作业
多级目录菜单
menu = {
'北京':{
'海淀':{
'五道口':{
'soho':{},
'网易':{},
'google':{}
},
'中关村':{
'爱奇艺':{},
'汽车之家':{},
'youku':{},
},
'上地':{
'百度':{},
},
},
'昌平':{
'沙河':{
'老男孩':{},
'北航':{},
},
'天通苑':{},
'回龙观':{},
},
'朝阳':{},
'东城':{},
},
'上海':{
'闵行':{
"人民广场":{
'炸鸡店':{}
}
},
'闸北':{
'火车战':{
'携程':{}
}
},
'浦东':{},
},
'山东':{},
}
current_layer = menu
layers = [menu] #储存上级目录
while True:
for i in current_layer:
print(i)
choice = input('>>>:').strip()
if choice == 'back':
current_layer = layers[-1]
layers.pop()
elif choice == 'quit':
break
elif choice not in current_layer: continue
else:
layers.append(current_layer) #保存上级目录
current_layer = current_layer[choice]
集合
集合添加
t.add('x')
t.update([1,8,11,12]) #添加多项
集合删除
t.remove('x')
集合查询
len(x)
'x' in s #x是否在s集合中
s.isubset(t)
s <= t #判断s是否是t的子集
s.isuperset(t)
s >= t
集合操作
s.copy() #返回一个s的浅复制
s = set([3,5,7,9])
t = set([3,7,8,10])
a = t | s #t和s的并集
t.union(s)
b = t & s #t和s的交集
t.intersection(s)
c = t - s
t.difference(s)
d = t ^ s #t和s的异或(项在t或s中,但不会同时在二者中出现)
t.symetric_difference(t)