栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python之与字典有关的函数的使用,字典的遍历

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python之与字典有关的函数的使用,字典的遍历

字典中元素的个数计算:len(字典名)
举例:

person={"姓名":"张三","年龄":20,"性别":"男"}
print(len(person))
3

字典中的键名:字典名.keys()
举例:

person={"姓名":"张三","年龄":20,"性别":"男"}
print(person.keys())
persons=person.keys()
print(type(persons))
dict_keys(['姓名', '年龄', '性别'])

加粗样式字典中的键值:字典名.values()
举例:

person={"姓名":"张三","年龄":20,"性别":"男"}
print(person.values())
persons=person.values()
print(type(persons))
dict_values(['张三', 20, '男'])

字典的键名以及对应的键值:字典名.items()

person={"姓名":"张三","年龄":20,"性别":"男"}
print(person.items())
persons=person.items()
print(type(persons))
dict_items([('姓名', '张三'), ('年龄', 20), ('性别', '男')])

字典的遍历:键名,键值,键名对应键值的遍历。
方法一:
举例:

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
性别 男
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/981999.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号