python基础知识整理字典(四)

                                                                                                ------ 字典------

字典{}:是一系列键—值对 每个键 都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典
字典特点:无序 键值对
alien_0 = {‘color’: ‘green’, ‘points’: 5}

访问字典中的值
要获取与键相关联的值,可依次指定字典名和放在方括号内的键
alien_0 = {‘color’: ‘green’}
print(alien_0[‘color’])

添加键值对
alien_0 = {‘color’: ‘green’, ‘points’: 5}
print(alien_0)
alien_0[‘x_position’] = 0
alien_0[‘y_position’] = 25
print(alien_0)

修改字典中的值
alien_0 = {‘color’: ‘green’}
print("The alien is " + alien_0[‘color’] + “.”)
alien_0[‘color’] = ‘yellow’
print("The alien is now " + alien_0[‘color’] + “.”)

删除键值对
对于字典中不再需要的信息,可使用del 语句将相应的键—值对彻底删除。使用del 语句时,必须指定字典名和要删除的键
alien_0 = {‘color’: ‘green’, ‘points’: 5}
print(alien_0)
del alien_0[‘points’]
print(alien_0)

遍历所有的键值对
user_0 = {
‘username’: ‘efermi’,
‘first’: ‘enrico’,
‘last’: ‘fermi’,
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)

遍历字典中的所有键
favorite_languages = {
‘jen’: ‘python’,
‘sarah’: ‘c’,
‘edward’: ‘ruby’,
‘phil’: ‘python’,
}
for name in favorite_languages.keys():
print(name.title())

favorite_languages = {
‘jen’: ‘python’,
‘sarah’: ‘c’,
‘edward’: ‘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() + “!”)

按顺序遍历字典中的所有键
favorite_languages = {
‘jen’: ‘python’,
‘sarah’: ‘c’,
‘edward’: ‘ruby’,
‘phil’: ‘python’,
}
for name in sorted(favorite_languages.keys()):
print(name.title() + “, thank you for taking the poll.”)
for name in favorite_languages.keys():
print(name,end=’ ')

遍历字典中的所有值
favorite_languages = {
‘jen’: ‘python’,
‘sarah’: ‘c’,
‘edward’: ‘ruby’,
‘phil’: ‘python’,
}
print(“The following languages have been mentioned:”)
for language in favorite_languages.values():
print(language.title())

嵌套字典列表
例一
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,end=’ ')

例二
创建一个用于存储外星人的空列表
aliens = []
创建30个绿色的外星人
for alien_number in range(30):
new_alien = {‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
aliens.append(new_alien)
for alien in aliens[:20]:
print(alien)
print("…")

例三
创建一个用于存储外星人的空列表
aliens = []

创建30个绿色的外星人

for alien_number in range (0,30):
new_alien = {‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien[‘color’] == ‘green’:
alien[‘color’] = ‘yellow’
alien[‘speed’] = ‘medium’
alien[‘points’] = 10

显示前五个外星人

for alien in aliens[0:5]:
print(alien)
print("…")

在字典中存储列表
存储所点比萨的信息
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)

favorite_languages = {
‘jen’: [‘python’, ‘ruby’],
‘sarah’: [‘c’],
‘edward’: [‘ruby’, ‘go’],
‘phil’: [‘python’, ‘haskell’],
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + “'s favorite languages are:”)
for language in languages:
print("\t" + language.title())

字典中存储字典
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())
在这里插入图片描述在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值