网络编程
位置:首页>> 网络编程>> Python编程>> Python中字典及遍历常用函数的使用详解

Python中字典及遍历常用函数的使用详解

作者:从未止步..  发布时间:2021-06-25 13:06:03 

标签: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
性别 男

来源:https://blog.csdn.net/m0_64365419/article/details/125402009

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com