脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python字典 dict几种遍历方式

Python字典 dict几种遍历方式

2022-02-25 00:03小小程序员ol Python

这篇文章主要给大家分享的是Python字典 dict几种遍历方式,文章主要介绍使用 for key in dict遍历字典、使用for key in dict.keys () 遍历字典的键等内容,需要的朋友可以参考一下,希望对你有所帮助

1.使用 for key in dict遍历字典

可以使用for key in dict遍历字典中所有的键

?
1
2
3
4
5
6
7
8
x = {'a': 'A', 'b': 'B'}
for key in x:
    print(key)
 
 
# 输出结果
a
b

2.使用for key in dict.keys () 遍历字典的键

字典提供了 keys () 方法返回字典中所有的键

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# keys
book = {
    'title': 'Python',
    'author': '-----',
    'press': '人生苦短,我用python'
}
 
for key in book.keys():
    print(key)
 
# 输出结果
title
author
press

3.使用 for values in dict.values () 遍历字典的值

字典提供了 values () 方法返回字典中所有的值

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
'''
学习中遇到问题没人解答?小编创建了一个Python学习交流群:725638078
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
# values
book = {
    'title': 'Python',
    'author': '-----',
    'press': '人生苦短,我用python'
}
 
for value in book.values():
    print(value)
 
 
# 输出结果
Python
-----
人生苦短,我用python

4.使用 for item in dict.items () 遍历字典的键值对

字典提供了 items () 方法返回字典中所有的键值对 item
键值对 item 是一个元组(第 0 项是键、第 1 项是值)

?
1
2
3
4
5
6
7
8
9
10
x = {'a': 'A', 'b': 'B'}
for item in x.items():
    key = item[0]
    value = item[1]
    print('%s   %s:%s' % (item, key, value))
 
 
# 输出结果
('a', 'A')   a:A
('b', 'B')   b:B

5.使用 for key,value in dict.items () 遍历字典的键值对

元组在 = 赋值运算符右边的时候,可以省去括号

?
1
2
3
4
5
6
7
8
9
10
11
'''
学习中遇到问题没人解答?小编创建了一个Python学习交流群:725638078
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
item = (1, 2)
a, b = item
print(a, b)
 
 
# 输出结果
1 2

例:

?
1
2
3
4
5
6
7
8
x = {'a': 'A', 'b': 'B'}
for key, value in x.items():
    print('%s:%s' % (key, value))
 
 
# 输出结果
a:A
b:B

到此这篇关于Python字典 dict几种遍历方式的文章就介绍到这了,更多相关Python 字典 dict内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/python960410445/p/15510522.html

延伸 · 阅读

精彩推荐