欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

字典的学习2——参考Python编程从入门到实践

程序员文章站 2022-07-10 22:38:41
遍历字典 1. 遍历所有键值对 eg1: for key, value in user_0.items(): 也可简化为 for k, v in user_0.items(): 但对于这两个变量是可以使用任何名称,并不局限于此。 eg2: 打印出每个人喜欢的语言 2.遍历字典中的所有键 找出两位朋友 ......

遍历字典

1. 遍历所有键值对

eg1: 

user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("\nkey: " + key)
print("value: " + value)

for key, value in user_0.items(): 也可简化为 for k, v in user_0.items(): 但对于这两个变量是可以使用任何名称,并不局限于此。

eg2: 打印出每个人喜欢的语言

favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " + language.title() + ".")

2.遍历字典中的所有键

for name in favorite_languages.keys():
print(name.title())

或省略keys(),输出不变
for name in favorite_languages:
print(name.title())

找出两位朋友喜欢的语言:

friends = ['phil', 'sarah']
for name in favorite_languages.keys():
if name in friends:
print("hi " + name.title() + ", i see your favorite language is " + favorite_languages[name].title() + "!")

确定某个人是否接受了调查

if 'eric' not in favorite_languages.keys():
print("erin, please take our poll!")

3. 按顺序遍历字典中的所有键

for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")

调用sorted( )函数让字典中所有键在遍历前排序。

4. 遍历字典中的所有值

print('the following languages have been mentioned:')
for language in favorite_languages.values():
print(language.title())

运行结果:

the following languages have been mentioned:
python
c
ruby
python

打印出了字典中的所有值,但字典中的值是可以重复的,结果也就出现了重复,为此可以使用集合set( )提出重复:

print('the following languages have been mentioned:')
for language in set(favorite_languages.values()):
print(language.title())

运行结果:

the following languages have been mentioned:
python
ruby
c

note: 遍历字典时,键值的返回顺序是不定的,键和值的对应是固定。