笔记出处(学习UP主视频记录) https://www.bilibili.com/video/av35698354?p=12
6.3 遍历字典
6.3.1 遍历所有的键-值对
user_0 = { 'username': 'efermi', 'first': 'emrico', 'last': 'fermi', } for key, value in user_0.items(): print(" Key: " + key) print("Value: " + value)
Key: username
Value: efermi
Key: first
Value: emrico
Key: last
Value: fermi
user_0 = { 'username': 'efermi', 'first': 'emrico', 'last': 'fermi', } for k, v in user_0.items(): print(" Key: " + k) print("Value: " + v)
Key: username
Value: efermi
Key: first
Value: emrico
Key: last
Value: fermi
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() + ".")
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.
6.3.2 遍历字典中的所有键
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for name in favorite_languages.keys(): print(name.title())
Jen
Sarah
Edward
Phil
6.3.3 按顺序遍历字典中的所有键
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for name in sorted(favorite_languages.keys()): print(name.title() + ", thank you for taking the poll.")
Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.
6.3.4 遍历字典中的所有值
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } print("The following languages have been mentioned:") for language in favorite_languages.values(): print(language.title())
Python
C
Ruby
Python
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } print("The following languages have been mentioned:") for language in set(favorite_languages.values()): print(language.title())
# set可以找出列表中独一无二的元素,并使用这些元素来创建一个集合
The following languages have been mentioned:
C
Python
Ruby
Caesar卢尚宇
2020年3月17日