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

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

服务器之家 - 脚本之家 - Python - python字典遍历数据的具体做法

python字典遍历数据的具体做法

2021-12-14 00:17laozhang Python

在本篇文章里小编给大家整理了一篇关于python字典遍历数据的具体做法及相关代码,有需要的朋友们可以跟着学习下。

说明

1、for循环遍历:使用for循环直接遍历字典,此时得到字典的key值。

2、keys():用于获取字典的key值。获得的类型是dict_keys,然后使用list()进行强制转换,获得key值,或者使用for循环遍历。

3、values():用于获取字典的values值,类型为dict_values,然后使用==list()==强制转换,获取values值,也可以使用for循环遍历。

4、items():用于获取字典中的所有键值对。获得的类型是dict_items,内容是由key值和value值组成的元组类型。

实例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 定义一个字典
dic = {'Name': '张三', 'Gender': '男', 'Age': 20, 'Height': 177}
 
 
# for 循环遍历字典内容
for i in dic:
    print(i, ' : ', dic[i])
print('===' * 26)
 
# dic.keys 遍历
print(type(dic.keys()))   # 打印 dic.keys() 得到的数据类型
for i in dic.keys():
    print(i, ' : ', dic[i])
print('===' * 26)
 
# dic.values() 遍历
print(type(dic.values()))
for i in dic.values():
    print(i)
print('===' * 26)
 
# dic.items() 遍历
print(dic.items())
for i in dic.items():   # 使用二次循环进行遍历,第一次获得元组的内容,第二次获得具体的值
    for j in i:
        print(j, end=' : ')
    print()

实例扩展:

遍历字典中的每一个key

?
1
2
3
4
5
6
7
8
9
my_dict = {'name': '王五', 'age': 20}
 
# 遍历字典中的每一个key
for key in my_dict.keys():
    print(key)
 
# 输出
>> name
>> age

遍历字典中的每一个value

?
1
2
3
4
5
6
7
8
9
my_dict = {'name': '王五', 'age': 20}
 
# 遍历字典中的每一个
for value in my_dict.values():
    print(value)
 
# 输出
>> 王五
>> 20

遍历字典中的每项数据,每项数据是键值对,把键值对封装到元祖里面

?
1
2
3
4
5
6
7
8
9
my_dict = {'name': '王五', 'age': 20}
 
# 遍历字典中的每项数据,每项数据是键值对,把键值对封装到元祖里面
for item in my_dict.items():
    print(item)
 
# 输出
>> ('name', '王五')
>> ('age', 20)

到此这篇关于python字典遍历数据的具体做法的文章就介绍到这了,更多相关python字典如何遍历数据内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.py.cn/jishu/jichu/31638.html

延伸 · 阅读

精彩推荐