python 遍历字典的item ,遍历字典的key 和 value
1 遍历字典子元素
dictionary = {"one": "语文", "two": "数学", "three": "英语", "four": "物理", "five": "化学"}
for key in dictionary.items():
print(key)
打印结果
2 单独遍历出key,value 可以使用for in
dictionary = {"one": "语文", "two": "数学", "three": "英语", "four": "物理", "five": "化学"}
# 如果想单独遍历出key,value 可以使用for in
for key, value in dictionary.items():
# 遍历字典的key
print(key)
# 遍历字典的value
print(value)
打印结果
3 或者直接使用for in 遍历出key 和value
dictionary = {"one": "语文", "two": "数学", "three": "英语", "four": "物理", "five": "化学"}
for key in dictionary:
# 遍历字典的key
print(key)
# 遍历字典的value
print(dictionary[key])
打印结果
4 遍历出 value
dictionary = {"one": "语文", "two": "数学", "three": "英语", "four": "物理", "five": "化学"}
# dictionary.values() 是获取字典的value 所以可以使用它遍历出values 如下
for values in dictionary.values():
print(values)
打印结果
还没有评论,来说两句吧...