一、字典建立、修改、删除及遍历
1)建立字典方式
#字典{}键-值,键名称必须带引号
#建空字典再添加
dic_city={}
dic_city['name']='TJ'
dic_city['num']=12000
dic_city['lever']=2
print(dic_city)
#直接建
dic_cus={'name':'Ana','age':27,'gender':'male'}
print(dic_cus)
2)修改字典
#修改字典,直接修改或间接修改
dic_cus['age']=28
print(dic_cus)
if dic_cus['age']<=20 and dic_cus['gender']=='male':
dic_cus['type']='younger'
elif dic_cus['age']>20 and dic_cus['age']<35 and dic_cus['gender']=='male':
dic_cus['type']='childbear'
else:
dic_cus['type']='older'
print(dic_cus)
print('She type is '+dic_cus['type'])
3)删除字典内容
#删除字典内容建-值对用del
del dic_city['num']
print(dic_city)
4)多行字典输出格式
#多行内容字典输出
dic_num={
'Ana':3,
'eliy':5,
'tracy':7,
'smail':3,
'nancy':2
}
print('Ana love num is:'
+str(dic_num['Ana'])
+'.')
print()
5)遍历字典元素
#遍历全部输出元素,和列表不同是要加.items()
for name,num in dic_num.items():
print(name.title()+' love num is:'+str(num))
name_is=['Ana','smail']
print()
#遍历所有键,可用keys()相当于一个列表;还可按顺序遍历sorted
for name1 in dic_num.keys():
print(name1.title())
if name1 in name_is:
print(name1.title()+' is allowed')
else:
print(name1.title()+'is not allowed')
print()
for name2 in sorted(dic_num.keys()):
print(name2.title())
print()
#遍历所有值
for num1 in dic_num.values():
print(str(num1))
print()
#1.按顺序
for num2 in sorted (dic_num.values()):
print(str(num2))
print()
#2.一个值唯一的集合
for num3 in set (dic_num.values()):
print(str(num3))
print()
二、字典嵌套
#1.在列表中存储字典及改变值,循环调用同列表
cat_names=[]
for cat in range(1,5):
dic_cat={'age':3,'color':'yellow','like':'milk'}
cat_names.append(dic_cat)
print()
for cat in cat_names[1:3]:
if cat['color']=='yellow':
cat['color']='white'
cat['like']='water'
cat['age']=5
for cat in cat_names[0:4]:
print(cat)
print()
for cat in cat_names[1:4]:
if cat['color']=='white':
cat['color']='black'
cat['like']='milk'
elif cat['color']=='yellow':
cat['color']='white'
cat['like']='water'
for i in cat_names:
print(i)
#2.存储字典中的列表,循环调用同字典,需明确键['']
love_language={
'Ana':'two',
'langu':['R','Python']
}
print(love_language['langu'])
print()
print(love_language['Ana']+' love :')
for langui in love_language['langu']:
print('\t'+langui)
love_language={
'Ana':'R',
'cici':['R','Python']
}
for namei,langus in love_language.items():
print('\n'+namei.title()+'love language is :')
for lai in langus:
print(lai)
#3.存储在字典里的字典,每个用户的字典结构相同
user={'Ana':{'age':23,'F/M':'M'},
'SS':{'age':30,'F/M':'F'}}
for name,value in user.items():
print(name+' '+str(value['age'])+' '+value['F/M'])