此程序的目的在于,正确而简单的访问字典的键与值

 favorite_languages={
'jen':['python','c'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python','java'],
}
#古老的方法访问字典中键与值
for element in favorite_languages:
print(element +"'s favorite languages are:")
print("\t"+str(favorite_languages[element]))
# 正确的方法访问键与值
for name,languages in favorite_languages.items():
print("\n"+name.title()+"'s favorite languages are:")
for language in languages:
print("\t"+language.title())
 for name,languages in favorite_languages.items():
if len(languages) == 1:
print("\n"+name.title()+"'s favorite languages is:")
else:
print("\n"+name.title()+"'s favorite languages are:")
for language in languages:
print("\t"+language.title())

1  代码中12-15行代码是正确而又简便的访问字典键与值的方式。注意for 后面可以跟两个变量,一个用来访问键,一个用来访问值。

2 .item()类可以方便的完成这种访问,实际上.item()返回了两个列表,一个给了name,另一个给了languages.

3  注意第二个for循环的位置

05-04 02:49