Python初学——字典

Python初学——字典字典:键——值对应1、添加与删减:{'color':'green','score':5,'color2':'yellow','color1':'red','c

大家好,欢迎来到IT知识分享网。Python初学——字典"

字典:

键——值对应

dictory={
'color':'green',
'score':5,
'color2':'yellow'
}

1、添加与删减:

dictory['color1']='red'
dictory['color3']='white'
print(dictory)
del dictory['score']
print(dictory)
·································

{‘color’: ‘green’, ‘score’: 5, ‘color2’: ‘yellow’, ‘color1’: ‘red’, ‘color3’: ‘white’}
{‘color’: ‘green’, ‘color2’: ‘yellow’, ‘color1’: ‘red’, ‘color3’: ‘white’}

 

2、遍历:

遍历所有的键与值:
for key,value in dictory.items():
print('\n'+key)
print(value)
只遍历键:采用keys()方法
for key in dictory.keys():
print(key)
······························

color
color2
color1
color3

只遍历值:采用value()方法:

for value in dictory.values():
print(value)
······························

green
yellow
red
white

 

3、字典的嵌套:

 

我们可以将列表存储在字典中

pizza={
'crust':'thick',
'top':['mushroom','cheese']
}
print("You ordered a"+pizza['crust']+"-crust pizza"+"with the following top:")
for top in pizza['top']:
print("\t"+top)
·····································

You ordered athick-crust pizzawith the following top:
mushroom
cheese

 

也可以在字典中存储字典:

用户组有两个用户,每个用户分别有一个字典包含他们的个人信息

users={
'aestin':{
'first':'albert',
'second':'einst',
'location':'pronceton'
},
'mcurin':{
'first': 'maric',
'second': 'scare',
'location': 'paris'
}
}
for username,user_info in users.items():
print("\nusername:"+username)
full_name=user_info['first']+" "+user_info['second']
location=user_info['location']
print("\tFull name:"+full_name.title())
print("\tLocation:"+location.title())

 ·········································································

username:aestin
Full name:Albert Einst
Location:Pronceton

username:mcurin
Full name:Maric Scare
Location:Paris

 

 


                                                        

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/31571.html

(0)
上一篇 2023-11-11 19:15
下一篇 2023-11-11 22:45

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信