Python 字典遍历:使用 for 循环访问键值对
在 Python 中,可以使用 for 循环遍历字典,通过键值对的方式访问字典中的元素。
举一个例子,假设有一个字典存储了学生的姓名和年龄:
students = {'Alice': 18, 'Bob': 20, 'Charlie': 19, 'David': 18}
可以使用 for 循环遍历该字典,并打印每个学生的姓名和年龄:
for name, age in students.items():
print(name + ' is ' + str(age) + ' years old.')
输出结果为:
Alice is 18 years old.
Bob is 20 years old.
Charlie is 19 years old.
David is 18 years old.
在循环中,使用 items() 方法获取字典中的键值对,然后将键和值分别赋值给变量 name 和 age,最后使用 print() 函数打印出每个学生的姓名和年龄。
原文地址: https://www.cveoy.top/t/topic/nv1w 著作权归作者所有。请勿转载和采集!