[Python编程从入门到实战] 第6章 字典

使用字典

在Python中字典是一系列键值对。每个键都与一个值相关联,可以通过访问键来访问与之相关联的值。任何对象都可以用作字典中的值。
python只保存键值对的关系,不关心键值对在字典中的顺序。

访问字典中的值

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

new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")
# You just earned 5 points!

添加一对键值对

要添加一对键值对,可以依次指定字典名、用方括号括起的键和相关联的值。

alien_0 = {'color': 'green', 'points': 5}
print(alien_0)

alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

# {'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)

# 修改字典中的值
alien_0['color'] = 'yellow'
print(alien_0)

# 删除键值对
alien_0 = {'color': 'green', 'points': 5}
del alien_0['points']

# 遍历字典
alien_0 = {'color': 'green', 'points': 5}
for key, value in alien_0.items():	# 将键值对存储到key和value中
	pass
alien_0.items()						# 返回一个键值对列表

for key in alien_0.keys():
	pass

for name in sorted(favorite_languages.keys()):
	pass							# 按顺序遍历字典中的所有键

for language in set(favorite_languages.values()):
	pass							# set()集合类似于列表,但没有重复值

嵌套

列表中嵌套字典、字典中嵌套列表和字典中嵌套字典。

# 列表中嵌套字典
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'green', 'points': 5}
alien_2 = {'color': 'green', 'points': 5}

aliens = [alien_0, alien_1, alien_2]

for alien in aliens:
	print(alien)

# 字典中存储列表
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',
	},
}
发布了7 篇原创文章 · 获赞 0 · 访问量 177

猜你喜欢

转载自blog.csdn.net/qq_40355068/article/details/104091908