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

字典中元素的个数计算: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
性别 男
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

从未止步..

谢谢你的打赏,我会继续努力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值