Python学习——字典

字典

思维导图

在这里插入图片描述

代码

# 字典 键_值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
# 修改字典
alien_0 = {'color': 'green'}
# 访问字典 依次指定字典名和放在方括号内的键
print(alien_0['color'])
# 添加键_值对
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
# 创建一个空字典
alien_0 = {}
print(alien_0)
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
# 修改字典中的值
print("The alien is " + alien_0['color'] + '.')
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + '.')
#
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original x_position: " + str(alien_0['x_position']))
# 向右移动外星人
# 根据外星人当前速度决定将其移动多远
if alien_0['speed'] == 'slow':
    x_increment = 1
elif alien_0['speed'] == 'medium':
    x_increment = 2
else:
    # 这个外星人的速度一定很快
    x_increment = 3
# 新位置等于老位置加上增量
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New x-position: " + str(alien_0['x_position']))
# 删除键—值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
# 由类似对象组成的字典
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python'
}
print("Sarah's favorite language is " + favorite_languages['sarah'].title() + '.')
for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is " + language.title() + '.')
# 遍历字典中的所有键 .keys()
for name in favorite_languages.keys():
    print(name.title())
friends = ['phil', 'sarah']
if 'erin' not in favorite_languages.keys():
    print("Erin,please take our poll!")
for name in favorite_languages.keys():
    print(name.title())
    # 把name当做变量传入
    if name in friends:
        print(" Hi " + name.title() +
              ", I see you favorite language is " +
              favorite_languages[name].title() + "!")
# 按顺序遍历字典中的所有键
for name in sorted(favorite_languages.keys()):
    print(name.title() + ",thank you for taking the poll.")
# 遍历字典中的所有值 .values()
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)
# 创建30个外星人
aliens = []
# 等同于range(0, 30)
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
for alien_number in range(30):
    aliens.append(new_alien)
for alien in aliens[:5]:
    print(alien)
print("...")
# len函数获得列表的长度;str函数把里面的内容转换为字符串
print("Total number of aliens: " + str(len(aliens)))
for alien in aliens[:3]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10
    elif alien['color'] == 'yellow':
        alien['color'] = 'red'
        alien['speed'] = 'fast'
        alien['points'] = 15
for alien in aliens[:5]:
    print(alien)
# 存储所点比萨的信息
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 language 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())

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值