Python中字典及遍历常用函数的使用详解
作者:从未止步.. 时间:2021-06-25 13:06:03
字典中元素的个数计算
len(字典名)
举例:
person={"姓名":"张三","年龄":20,"性别":"男"}
print(len(person))
输出:
3
字典中的键名
字典名.keys()
举例:
person={"姓名":"张三","年龄":20,"性别":"男"}
print(person.keys())
persons=person.keys()
print(type(persons))
输出:
dict_keys(['姓名', '年龄', '性别'])
<class 'dict_keys'>
加粗样式字典中的键值
字典名.values()
举例:
person={"姓名":"张三","年龄":20,"性别":"男"}
print(person.values())
persons=person.values()
print(type(persons))
输出:
dict_values(['张三', 20, '男'])
<class 'dict_values'>
字典的键名以及对应的键值
字典名.items()
person={"姓名":"张三","年龄":20,"性别":"男"}
print(person.items())
persons=person.items()
print(type(persons))
输出:
dict_items([('姓名', '张三'), ('年龄', 20), ('性别', '男')])
<class 'dict_items'>
字典的遍历
键名,键值,键名对应键值的遍历。
方法一
举例:
person={"姓名":"张三","年龄":20,"性别":"男"}
persons_1=person.keys()
persons_2=person.values()
persons_3=person.items()
for a in persons_1://键名的遍历
print(a,end=' ')
print("\n")
for b in persons_2://键值的遍历
print(b,end=' ')
print("\n")
for c in persons_3://键名与对应的键值的遍历
print(c,end=' ')
输出:
姓名 年龄 性别
张三 20 男
('姓名', '张三') ('年龄', 20) ('性别', '男')
方法二
person={"姓名":"张三","年龄":20,"性别":"男"}
for keys in person.keys()://键名的遍历
print(keys,end=' ')
print("\n")
for values in person.values()://键值的遍历
print(values,end=' ')
print("\n")
for key,values in person.items()://键名与对应的键值的遍历
print(key,values)
输出:
姓名 年龄 性别
张三 20 男
姓名 张三
年龄 20
性别 男
来源:https://blog.csdn.net/m0_64365419/article/details/125402009
标签:Python,字典,遍历
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
简单了解Python字典copy与赋值的区别
2022-07-16 11:35:52
python 获取微信好友列表的方法(微信web)
2022-02-20 10:05:21
制作全局临时表
2010-06-11 13:36:00
Python如何使用print()函数输出格式化字符串
2021-03-09 22:43:41
![](https://img.aspxhome.com/file/2023/5/86345_0s.png)
以一段代码为实例快速入门Python2.7
2021-04-24 05:00:06
python二维列表一维列表的互相转换实例
2023-07-09 10:27:40
Python面向对象特殊成员
2021-07-03 12:05:48
anaconda创建、查看、激活与删除虚拟环境指令总结
2023-04-09 13:01:23
![](https://img.aspxhome.com/file/2023/1/134601_0s.jpg)
Python激活Anaconda环境变量的详细步骤
2023-01-02 18:45:20
![](https://img.aspxhome.com/file/2023/0/76870_0s.png)
Python实现npy/mat文件的保存与读取
2023-07-22 08:49:48
![](https://img.aspxhome.com/file/2023/8/83738_0s.png)
详解Python中的Cookie模块使用
2023-01-02 21:30:39
![](https://img.aspxhome.com/file/2023/0/107290_0s.jpg)
python 模拟网站登录——滑块验证码的识别
2023-04-17 16:16:29
![](https://img.aspxhome.com/file/2023/8/107798_0s.png)
几个SQL SERVER应用问题解答
2008-01-01 19:12:00
python接口自动化使用requests库发送http请求
2023-08-02 02:04:37
![](https://img.aspxhome.com/file/2023/0/61490_0s.png)
python3 求约数的实例
2023-12-29 03:18:59
iis7 ASP+Access数据库连接错误
2011-03-08 10:41:00
django haystack实现全文检索的示例代码
2021-04-08 05:00:59
![](https://img.aspxhome.com/file/2023/5/128285_0s.png)
python实现简单的井字棋游戏(gui界面)
2023-03-06 23:16:01
![](https://img.aspxhome.com/file/2023/3/83973_0s.png)
Python深入学习之上下文管理器
2023-03-27 19:09:43
django2.0扩展用户字段示例
2023-08-31 11:10:10