python 字典4

本文详细介绍了Python中字典的基本操作,包括创建、读取、更新、删除键值对,以及如何遍历字典。此外,还探讨了字典的嵌套使用,如在字典中存储列表和字典,提供了丰富的示例代码。

使用字典

字典是一系列键 - 值对。每个键都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典

字典用放在花括号{ } 中的一系列键—值对表示,用来记录坐标值挺好

alien_0 = {'color': 'green', 'points': 5}
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.

删除键 - 值对

永久删除

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

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

遍历字典

遍历字典时,键-值对的返回顺序也与存储顺序不同。 Python不关心键—值对的存储顺序,而只跟踪键和值之间的关联关系。

  • 方法items(),它返回一个键—值对列表
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

只遍历所有键:方法key()

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

for name in favorite_languages.keys():
	print(name.title())#title用了首字母大写

#结果	
Jen
Sarah
Phil
Edward

  • 遍历字典时,会默认遍历所有的键,因此,如果将上述代码中的for name in favorite_languages.keys():替换为for name in favorite_languages:,输出将不变。
    如果显式地使用方法keys()可让代码更容易理解,你可以选择这样做,但如果你愿意,也可省略它。
  • 方法keys()并非只能用于遍历;实际上,它返回一个列表,其中包含字典中的所有键,就是方括号那个

只遍历所有值:方法values()

同上,不赘述

  • 字典中的元素可被方法sorted() 来获得按特定顺序排列的键列表的副本

嵌套

下面的代码创建一个包含三个外星人的列表:

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}

更符合现实的情形是,外星人不止三个,且每个外星人都是使用代码自动生成的。在下面的示例中,我们使用range()生成了30个外星人:

# 创建一个用于存储外星人的空列表
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)))

#结果
{'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

在字典中存储列表

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

#结果
Jen's favorite languages are:
	Python
	Ruby
	
Sarah's favorite languages are:
	C
	
Phil's favorite languages are:
	Python
	Haskell
	
Edward's favorite languages are:
	Ruby
	Go

在字典中存储字典

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

注意

  • 表示每位用户的字典的结构都相同,虽然Python并没有这样的要求,但这使得嵌套的字典处理起来更容易。倘若表示每位用户的字典都包含不同的键, for循环内部的代码将更复杂
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值