'''遍历字典'''
fav_lag={
'aerfa':'C',
'Betha':'python',
'Kevin':'JAVA',
'olIver':'Lingo'}
for name, lag in fav_lag.items(): # items() 返回的是键值对,但是顺序与存储顺序无关
print('\n',name,"'s favourite language is",lag)
print('\n\n')
for name , lag in sorted(fav_lag.items(),reverse=True): #按照的键字母的 ASCII 从小到大(默认)
print('\n',name.title(),"'s favourite language is",lag.upper())
'''遍历字典内的键'''
for name in fav_lag.keys(): #keys() 返回键 同样顺序规律同items()
print('\n',name.upper())
for lag in fav_lag.values(): #values() 返回值 顺序同上
print('\n',lag.lower())
names1=['phil','Betha','aaa','olIver']
for name in names1:
if name in fav_lag.keys(): #name 可以当做变量引用出对应的 值
print('\n',name,'You are in the list','and your favourite language is',fav_lag[name])
fav_lag['Neil wen']='python'
'''for lag in fav_lag.values():
print('\n',lag) #不忽略重复项'''
for lag in set(fav_lag.values()): #set() 相当于集合,即各元素之间不能相同
print('\n',lag) #在set()外加 sorted()依然可行
Python初学者之路--遍历字典
最新推荐文章于 2023-10-08 08:31:35 发布