网络编程
位置:首页>> 网络编程>> Python编程>> Python 如何读取字典的所有键-值对

Python 如何读取字典的所有键-值对

作者:a411178010  发布时间:2021-05-21 10:06:53 

标签:Python,字典的键,值对

如果字典中存储了一些值,我想要取出来该怎么操作呢?

1、我要取出字典中所有的键-值对

取出字典中所有的键-值对时,可以使用items()返回一个键值对列表,并配合for循环进行遍历


#创建一个存储一个学生的信息,通过遍历可以取出所有信息
student={'name':'xiaoming','age':11,'school':'tsinghua'}
for key,value in student.items():
   print(key+':'+str(value))

输出:

age:11

name:xiaoming

school:tsinghua

注意:

遍历出的返回值输出和存储的顺序不一样,输出顺序每次都会变化

在for循环中key和value两个变量需要使用逗号‘,'隔开

2、我要取出字典中的键

可以使用keys()方法取出字典中的键,不取对应的值


#创建一个人和对应喜欢水果的字典
people={'lifei':'apple','fanming':'peach','gaolan':'banana','hanmeimie':'peach'}
for name in people.keys():
   print(name)

输出:(顺序是随机的)

hanmeimie

gaolan

fanming

lifei

注意:keys()方法返回的是列表,要用列表的思维考虑问题

keys()返回的值顺序是不确定的,如果想按序排列,可以使用sorted()进行排序


#创建一个人和对应喜欢水果的字典
people={'lifei':'apple','fanming':'peach','gaolan':'banana','hanmeimie':'peach'}
for name in sorted(people.keys()):
   print(name)

输出:

fanming

gaolan

hanmeimie

lifei

3、我要取出字典中的值

可以使用values()取出字典中的值


#创建一个人和对应喜欢水果的字典
people={'lifei':'apple','fanming':'peach','gaolan':'banana','hanmeimie':'peach'}
for fruit in people.values():
   print(fruit)

输出:

peach

banana

peach

apple

注意,有没有看到上边输出的结果中有重复值,如果我想去除重复值怎么办呢,可以使用集合set() 去除重复值


#创建一个人和对应喜欢水果的字典
people={'lifei':'apple','fanming':'peach','gaolan':'banana','hanmeimie':'peach'}
for fruit in set(people.values()):
   print(fruit)

输出:

apple

peach

banana

练习

创建一个人员名单,有些人在水果字典中(承接上边的喜欢水果字典),有些人不在其中,对于已明确喜欢水果的,询问是否还需要其它的水果,对于未明确喜欢水果的,邀请他说出他喜欢的一种水果。


#创建一个人和对应喜欢水果的字典
people_fruit={'lifei':'apple','fanming':'peach','gaolan':'banana','hanmeimei':'peach'}
people=['lilei','caiming','hanmeimei','gaolan']
for name in people:
   if name in people_fruit.keys():
       print('您还需要其他的水果吗?')
   elif name not in people_fruit.keys():
       print('你能告诉我您喜欢的一种水果吗?')

输出:

你能告诉我您喜欢的一种水果吗?

你能告诉我您喜欢的一种水果吗?

您还需要其他的水果吗?

您还需要其他的水果吗?

来源:https://blog.csdn.net/a411178010/article/details/78548168

0
投稿

猜你喜欢

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