2.3 遍历字典
遍历字典的方式: 1遍历字典的所有的键-值对
2遍历字典的键
3遍历字典的值
2.3.1 遍历所有的键-值对
user_0 ={'username':'efermi','first':'enrico','last':'fermi',}
获悉字典user_0中的所有信息 for循环
键和值可以为任何名称(变量):k,v
键和值的名称可以根据实际情况来命名,这样容易理解
items() 函数以列表返回可遍历的(键, 值) 元组。
将字典中的键值对以元组存储,并将众多元组存在列表中。
可以用list 函数将items 返回的可迭代序列转化为列表
list_1 = user_0.items()list(list_1)
结果:
Out[2]:[('username','efermi'),('first','enrico'),('last','fermi')]
返回值:[(‘username’, ‘efermi’), (‘first’, ‘enrico’), (‘last’, ‘fermi’)]
for key,value in user_0.items():print("\nKey: "+ key)print("Value: "+ value)
结果:
Key: username
Value: efermi
Key: first
Value: enrico
Key: last
Value: fermi
或者
for k,v in user_0.items():print("\nKey: "+ key)print("Value: "+ value)
结果:
Key: last
Value: fermi
Key: last
Value: fermi
Key: last
Value: fermi
注意:键-值对的返回顺序可能与存储顺序不同,因为python不关心键-值对的存储顺序,
而只跟踪键和值之间的关联关系
favorite_languages ={'jen':'python','sarah':'c','edwaid':'ruby','phil':'python',}
键和值的名称可以根据实际情况来命名,这样容易理解
即键和值用描述性语句容易让人理解for循环中在作什么操作
for name,language in favorite_languages.items():print(name.title()+"'s favorite languages is "+
language.title()+".")
结果:
Jen's favorite languages is Python.
Sarah's favorite languages is C.
Edwaid's favorite languages is Ruby.
Phil's favorite languages is Python.
2.3.2 变量字典中的键 方法keys()
keys函数是Python的字典函数,它返回字典中的所有键所组成的一个可迭代序列。
使用keys()可以获得字典中所有的键。
使用list()函数可将keys()函数返回的可迭代序列转化为列表
favorite_languages ={'jen':'python','sarah':'c','edwaid':'ruby','phil':'python',}for name in favorite_languages.keys():print(name.title())# 这四行代码等价for name in favorite_languages:print(name.title())
结果:
Jen
Sarah
Edwaid
Phil
原因:遍历字典时,会默认遍历所有的键
方式keys()是显示的遍历键
将字典中的键存储到一个names列表中
names =[]
names_1 =list(favorite_languages.keys())for name in favorite_languages:
t_names = name
names.append(t_names)print(name.title())print(names)print(names_1)
结果:
Jen
Sarah
Edwaid
Phil
['jen','sarah','edwaid','phil']['jen','sarah','edwaid','phil']
使用键遍历的例子:使用当前的键来访问与之相关联的值
favorite_languages ={'jen':'python','sarah':'c','edwaid':'ruby','phil':'python',}
friends =['phil','sarah']for name in favorite_languages.keys():print(name.title())if name in friends:print(" Hi "+ name.title()+", I see your favorite language is "+
favorite_languages[name].title()+"!")
结果:
Jen
Sarah
Hi Sarah, I see your favorite language is C!
Edwaid
Phil
Hi Phil, I see your favorite language is Python!
使用keys()确定某个人是否接受了调查
favorite_languages ={'jen':'python','sarah':'c','edwaid':'ruby','phil':'python',}if'erin'notin favorite_languages.keys():print("Erin,please take our poll!")
结果:
Erin,please take our poll!
2.3.3 按顺序遍历字典中的所有键sorted函数
favorite_languages ={'jen':'python','sarah':'c','edwaid':'ruby','phil':'python',}for name insorted(favorite_languages.keys()):print(name.title()+", thank you for taking the poll.")
结果:
Edwaid, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.
2.3.4 遍历字典中的所有值方法values()
values()返回值:它返回字典中的所有值所组成的一个可迭代序列。
使用list可以去掉dict_value前缀,并转为列表
favorite_languages ={'jen':'python','sarah':'c','edwaid':'ruby','phil':'python',}print("The following languages have been mentioned: ")for language in favorite_languages.values():print(language.title())
结果:
The following languages have been mentioned:
Python
C
Ruby
Python
值去重,可考虑集和
print("The following languages have been mentioned: ")for language inset(favorite_languages.values()):print(language)
list_languages =list(favorite_languages.values())print(type(list_languages))print(list_languages)
结果:
The following languages have been mentioned:
python
ruby
c
<class'list'>['python','c','ruby','python']
python,c,ruby,python
另一种遍历值的方法
value = favorite_languages.values()print(",".join(i for i in value))
结果:
python,c,ruby,python
2-4 嵌套
定义:将一系列字典存储在列表中,或将列表作为值存储在字典中,称为嵌套
2-4-1 字典列表 将字典存到列表中
4、存储字典的列表
alien_0 ={'color':'green','points':5}
alien_1 ={'color':'yellow','points':10}
alien_2 ={'color':'red','points':15}
aliens =[alien_0,alien_1,alien_2]for alien in aliens:print(alien)
结果:
{'color':'green','points':5}{'color':'yellow','points':10}{'color':'red','points':15}
外星人有代码自动生成
创建一个用于存储外星人的空列表
aliens =[]
创建30个绿色的外星人
for alien_number inrange(30):
new_alien ={'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)# 显示前5个外星人for alien in aliens[:5]:print(alien)print(".......")
结果:
{'color':'green','points':5,'speed':'slow'}{'color':'green','points':5,'speed':'slow'}{'color':'green','points':5,'speed':'slow'}{'color':'green','points':5,'speed':'slow'}{'color':'green','points':5,'speed':'slow'}.......
显示创建了多个外星人
print("\nTotal number of aliens: "+str(len(aliens)))
结果:
Total number of aliens:30
外星人都有相同特征,python中每个外星人都是独立的,所以我们可以对每个外星进行修改
修改前3个外星人特征
创建一个用于存储外星人的空列表
aliens = []
创建30个绿色的外星人
for alien_number inrange(30):
new_alien ={'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)for alien in aliens[:3]:if alien['color']=='green':
alien['color']='yellow'
alien['speed']='medium'
alien['points']=10
显示前5个外星人
for alien in aliens[:5]:print(alien)print(".......")
结果:
{'color':'yellow','points':10,'speed':'medium'}{'color':'yellow','points':10,'speed':'medium'}{'color':'yellow','points':10,'speed':'medium'}{'color':'green','points':5,'speed':'slow'}{'color':'green','points':5,'speed':'slow'}.......
进一步扩展
创建一个用于存储外星人的空列表aliens = []
aliens =[]
创建30个绿色的外星人
for alien_number inrange(30):
new_alien ={'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)for alien in aliens[:3]:if alien['color']=='green':
alien['color']='yellow'
alien['speed']='medium'
alien['points']=10elif alien['color']=='yellow':
alien['color']='red'
alien['speed']='fast'
alien['points']=15
显示前5个外星人
for alien in aliens[:10]:print(alien)print(".......")
结果:
{'color':'yellow','points':10,'speed':'medium'}{'color':'yellow','points':10,'speed':'medium'}{'color':'yellow','points':10,'speed':'medium'}{'color':'green','points':5,'speed':'slow'}{'color':'green','points':5,'speed':'slow'}{'color':'green','points':5,'speed':'slow'}{'color':'green','points':5,'speed':'slow'}{'color':'green','points':5,'speed':'slow'}{'color':'green','points':5,'speed':'slow'}{'color':'green','points':5,'speed':'slow'}.......
应用领域:在网站中位每一个用户创建一个字典,并将字典存储到列表中
(每个字典的结构相同)
遍历列表处理数据
2.4.2 在字典中存储列表 即字典中放列表
5、存储列表的字典
存储所点比萨的信息
pizza ={'crust':'thick','toppings':['mushrooms','extra cheese'],}
概述所点的比萨
print("You ordered a "+ pizza['crust']+"-crust pizza "+"With the following toppings: ")for topping in pizza['toppings']:print('\t'+ topping)
结果:
You ordered a thick-crust pizza With the following toppings:
mushrooms
extra cheese
一个键关联多个值
favorite_languages ={'jen':['python','ruby'],'sarah':['c'],'edwaid':['ruby','go'],'phil':['python','haskell'],}for name,languages in favorite_languages.items():iflen(languages)==1:print("\n"+ name.title()+"'s favorite language is "+ languages[0].title())# 注意只有一个元素在列表中时,要用下标0来获取最后一个元素else:print("\n"+ name.title()+"'s favorite languages are: ")for language in languages:print("\t"+ language.title())
结果:
Jen's favorite languages are:
Python
Ruby
Sarah's favorite language is C
Edwaid's favorite languages are:
Ruby
Go
Phil's favorite languages are:
Python
Haskell
注意:列表和字典的嵌套层级不应该太多
太多的话,应该考虑有更简单的方法
6-4-3 在字典中存储字典
6、存储字典的字典
users ={'aeinstein':{'first':'albert','last':'einstein','location':'princeton',},'mcurie':{'first':"marie",'last':'curie','location':'paris',},}for username,user_info in users.items():print("\nUsername: "+ username)
full_name = user_info['first']+" "+ user_info['last']
location = user_info['location']print("\tFull name: "+ full_name.title())print("\tLocation: "+ location.title())
结果:
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris
总结:
1、字典的遍历方法:items()方法:键-值对遍历,返回的值是一个可以迭代序列,list()函数可以将其转为列表
keys()方法:键遍历,返回的值是一个可以迭代序列,list()函数可以将其转为列表
values()方法:值变量,返回值是一个可以迭代序列,list()函数可以将其转为列表
2、嵌套: 在列表中放字典,用于相同属性的对象
在字典中放列表,用于具有相同键的对象
在字典中放置地,用于复制对象
3、在Python对于可迭代的内置数据类型tuple,字符串若放在一个可迭代对象里面,最后一个字符串将以一个个字符变量,因为单个字符串也是可以迭代对象
例子:
tuple_2 =('你好!')for ele in list_2:print(ele)
结果:
你
好
!
版权归原作者 永恒@回忆 所有, 如有侵权,请联系我们删除。