chap6字典

字典

是一系列键—值对。每个键都与一个值相关联,你可以使用键来访问与之相关联的值。

alien = {'color': 'green', 'points': 5}
print(alien['color'])

键—值对是两个相关联的值。指定键时,Python将返回与之相关联的值。
键和值之间用冒号分隔,而键—值对之间用逗号分隔。

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

增加信息

alien_0['x_position'] = 0 
alien_0['y_position'] = 25

键—值对的排列顺序与添加顺序不同。Python不关心键—值对的添加顺序, 而只关心键和值之间的关联关系。

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

使用字典来存储用户提供的数据或在编写能自动生成大量键—值对的代码时,通常都需要先 定义一个空字典

修改值

alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = '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

删除

del alien_0['points']

对象

favorite_languages = { 
	'jen': 'python', 
	'sarah': 'c', 
	'edward': 'ruby', 
	'phil': 'python', 
	}
print("Sarah's favorite language is " + 
	favorite_languages['sarah'].title() + 
	".")

遍历

user_0 = {
	'username': 'efermi', 
	'first': 'enrico', 
	'last': 'fermi',
	}
for key, value in user_0.items(): 
	print("\nKey: " + key)
	print("Value: " + value)

即便遍历字典时,键—值对的返回顺序也与存储顺序不同。

遍历所有键值

for name in favorite_languages.keys(): 
	print(name.title())

遍历字典时,会默认遍历所有的键,因此,如果将上述代码中的for name in favorite_ languages.keys():替换为for name in favorite_languages:,输出将不变。

按顺序遍历所有键值sort()


for name in sorted(favorite_languages.keys()): 
	print(name.title() + ", thank you for taking the poll.")

遍历所有值

for language in favorite_languages.values():
	print(language.title())

使值不重复set()

for language in set(favorite_languages.values()): 
	print(language.title())

嵌套

可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典

字典列表

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

# 创建30个绿色的外星人
for alien_number in range(30):
	new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
	aliens.append(new_alien)

# 显示前五个外星人
for alien in aliens[:5]:
	print(alien) 
print("...")

# 显示创建了多少个外星人
print("Total number of aliens: " + str(len(aliens)))

在字典中存储列表

# 存储所点比萨的信息 
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)

每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表。

有时需要两个for循环

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())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值