python入门(四)

字典

示例

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

>>green
5

使用字典

在python中,字典是一系列键-值对。每个键都与一个值相关联,可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何python对象用作字典的值。
在python中,字典用放在花括号{ }中的一系列键-值对表示。键-值对是两个相关联的值。指定键时,python将返回与之相关联的值。键和值之间用冒号分隔,而键-值对之间用逗号分隔。在字典中,存储多少个键-值对都可以,最简单的键-值对只有一个键-值对。
要获取与键相关联的值,可依次指定字典名和放在方括号的键。

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)

{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}

要修改字典中的值,可依次指定字典名、用方括号括起的键以及与该键相关联的新值。

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.

对于字典中不再需要的信息,可使用del 语句将相应的键—值对彻底删除。使用del 语句时,必须指定字典名和要删除的键。

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',
}

遍历算法

要编写用于遍历字典的for 循环,可声明两个变量,用于存储键—值对中的键和值。对于这两个变量,可使用任何名称。
在遍历字典时,键—值对的返回顺序也与存储顺序不同。Python不关心键—值对的存储顺序,而只跟踪键和值之间的关联关系。

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

在不需要使用字典中的值时,方法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',
}
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() + "!")

>>Edward
Phil
Hi Phil, I see your favorite language is Python!
Sarah
Hi Sarah, I see your favorite language is C!
Jen

字典总是明确地记录键和值之间的关联关系,但获取字典的元素时,获取顺序是不可预测的。这不是问题,因为通常你想要的只是获取与键相关联的正确的值。要以特定的顺序返回元素,一种办法是在for 循环中对返回的键进行排序。可使用函数sorted() 来获得按特定顺序排列的键列表的副本:

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.")

>>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.

方法values() ,它可以返回一个值列表,而不包含任何键

favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
}

>>The following languages have been mentioned:
Python
C Python
Ruby

这种做法提取字典中所有的值,而没有考虑是否重复。涉及的值很少时,这也许不是问题,但如果被调查者很多,最终的列表可能包含大量的重复项。为剔除重复项,可使用集合(set)。集合 类似于列表,但每个元素都必须是独一无二的

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

通过对包含重复元素的列表调用set() ,可让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合。

嵌套

有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套 。可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。

# 字典列表
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)

实际情况使用示例:

# 创建一个用于存储信息的空列表
aliens = []
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)))

>>{'speed': 'slow', 'color': 'green', 'points': 5}
{'speed': 'slow', 'color': 'green', 'points': 5}
{'speed': 'slow', 'color': 'green', 'points': 5}
{'speed': 'slow', 'color': 'green', 'points': 5}
{'speed': 'slow', 'color': 'green', 'points': 5}
...
Total number of aliens: 30

有时候,需要将列表存储在字典中,而不是将字典存储在列表中。

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())

>>Username: aeinstein
	Full name: Albert Einstein
	Location: Princeton
Username: mcurie
	Full name: Marie Curie
	Location: Paris
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值