6 第六章 字典

发布时间 2023-03-27 12:23:49作者: Artwalker

一个简单的字典

alien_0 = {'color': 'green', 'points': 5}

print(alien_0['color'])
print(alien_0['points'])

使用字典

# 在Python中,字典用放在花括号 {} 中的一系列键—值对表示
alien_0 = {'color': 'green', 'points': 5}

# 获取与键相关联的值
alien_0 = {'color': 'green'}
print(alien_0['color'])
# green

# 字典中可包含任意数量的键—值对

# 添加键—值对: 字典是一种动态结构,可随时在其中添加键—值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)

alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
# 屏幕坐标系的原点通常为左上角
# 将该外星人放在屏幕左边缘,可将 x 坐标设置为0
# 将该外星人放在离屏幕顶部25像素的地方,可将 y 坐标设置为25
# {'color': 'green', 'points': 5}
# {'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}
# 键—值对的排列顺序与添加顺序不同
# Python不关心键—值对的添加顺序,而只关心键和值之间的关联关系

# 先创建空字典,然后添加键
alien_0 = {}

alien_0['color'] = 'green'
alien_0['points'] = 5

print(alien_0)
# {'color': 'green', 'points': 5}
# 使用字典来存储用户提供的数据或在编写能自动生成大量键—值对的代码时,
# 通常都需要先定义一个空字典

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

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']))
# Original x-position: 0
# New x-position: 2

# 删除键---值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)

del alien_0['points']
print(alien_0)
# {'color': 'green', 'points': 5}
# {'color': 'green'}

# 由类似对象组成的字典
favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
	}
# 将一个较大的字典放在了多行中;
# 其中每个键都是一个被调查者的名字,而每个值都是被调查者喜欢的语言;
# 确定需要使用多行来定义字典时,在输入左花括号后按回车键,
# 再在下一行缩进四个空格,指定第一个键—值对,并在它后面加上一个逗号,
# 定义好字典后,在最后一个键—值对的下一行添加一个右花括号,并缩进四个空格,使其与字典中的键对齐;
# 另外一种不错的做法是在最后一个键—值对后面也加上逗号,为以后在下一行添加键—值对做好准备

print("Sarah's favorite language is " +
	favorite_languages['sarah'].title() +
	".")
# Sarah's favorite language is C.
# 这个示例还演示了如何将较长的print 语句分成多行;
# 单词print 比大多数字典名都短,因此让输出的第一部分紧跟在左括号后面是合理的;
# 请选择在合适的地方拆分要打印的内容,并在第一行末尾加上一个拼接运算符(+ );
# 按回车键进入print 语句的后续各行,并使用Tab键将它们对齐并缩进一级;
# 指定要打印的所有内容后,在print 语句的最后一行末尾加上右括号

遍历字典

# 遍历所有的键—值对
user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
    }

for key, value in user_0.items():
    print("\nKey: " + key)
    print("Value: " + value)
# Key: last
# Value: fermi

# Key: first
# Value: enrico

# Key: username
# Value: efermi
# 遍历字典时,键—值对的返回顺序也与存储顺序不同;
# Python不关心键—值对的存储顺序,而只跟踪键和值之间的关联关系

# 遍历字典中的所有键
# 方法keys(): 返回一个列表,其中包含字典中的所有键
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
    
for name in favorite_languages.keys():
    print(name.title())
# Jen
# Sarah
# Phil
# Edward
# 遍历字典时,会默认遍历所有的键,因此,
# for name in favorite_languages.keys(): 与for name in favorite_languages: 等效

# 按顺序遍历字典中的所有键
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.")
# 使用函数 sorted() 来获得按特定顺序排列的键列表的副本
# Edward, 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.

# 遍历字典中的所有值
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())
# The following languages have been mentioned:
# Python
# C 
# Python
# Ruby

# 为剔除重复项,可使用集合(set)
# 集合类似于列表,但每个元素都必须是独一无二的
# 通过对包含重复元素的列表调用set(),
# 可让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}

print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
    print(language.title())
# The following languages have been mentioned:
# Python
# C 
# Ruby

嵌套

# 字典列表
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 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("...")
# {'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'}
# ...

# 在字典中存储列表
# 存储所点比萨的信息
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
# 列表和字典的嵌套层级不应太多。如果嵌套层级比前面的示例多得多,很可能有更简单的解决问题的方案

# 在字典中存储字典
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())

小结

如何定义字典,以及如何使用存储在字典中的信息;

如何访问和修改字典中的元素,以及如何遍历字典中的所有信息;

如何遍历字典中所有的键-值对、所有的键和所有的值;

如何在列表中嵌套字典、在字典中嵌套列表以及在字典中嵌套字典