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://www.cnblogs.com/KangZP/p/11131448.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值