字典的学习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: 遍历字典时,键值的返回顺序是不定的,键和值的对应是固定。
上一篇: 禽兽啊,没想到宅男口味这么重!
推荐阅读
-
测试代码的练习——python编程从入门到实践
-
类的练习2——python编程从入门到实践
-
函数的学习2——返回值&传递列表——参考Python编程从入门到实践
-
文件和异常练习2——python编程从入门到实践
-
《python编程:从入门到实践的》外星人入侵的代码
-
《Python编程:从入门到实践》个人学习笔记/心得(菜鸟瞎扯淡) Chapter2 变量和简单数据类型
-
在python编程从入门到实践中,第18章的问题(Django)
-
《Python编程从入门到实践》项目2 生成数据, 折线图, 随机漫步, pygal
-
元组的简单介绍——参考Python编程从入门到实践
-
字典的学习2——参考Python编程从入门到实践