Python编程 从入门到实践 第6章 字典

本文介绍了Python字典的基本用法,包括创建、修改键值对,使用del操作删除元素,以及遍历字典获取键值对、键和值的方法。通过实例演示了如何在程序中灵活运用字典数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 字典用大括号 {} 。键和值之间用冒号分隔,而键-值对之间用逗号分隔。

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

2 字典是一种动态结构,可随时在其中添加键-值对

>>> alien_0 = {'color':'green','points':5}
>>> alien_0['x_position'] = 0
>>> alien_0['y_position'] = 25
>>> print(alien_0)
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

3 del 不仅可以删除列表,也能删除字典

>>> print(alien_0)
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
>>> del alien_0['color']
>>> print(alien_0)
{'points': 5, 'x_position': 0, 'y_position': 25}

4 遍历字典,获取键-值对用 items() ,获取键用 keys() ,获取值用 values()

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

#输出
#Key: username
#Value: efermi
#
#Key: first
#Value: enrico
#
#Key: last
#Value: fermi
user_0 = {
	'username':'efermi',
	'first':'enrico',
	'last':'fermi',
}
for key in user_0.keys():
	print('Key: '+key)

#输出
#Key: username
#Key: first
#Key: last


for value in user_0.values():
	print('Value: '+value)

#输出
#Value: efermi
#Value: enrico
#Value: fermi

5 for循环里修改map,map应该是引用传递

aliens = [{'color':'green','points':12,'speed':'slow'},{'color':'green','points':12,'speed':'slow'}]
for alien in aliens:
	alien['color'] = 'red'
print(aliens)


#输出
#[{'color': 'red', 'points': 12, 'speed': 'slow'}, {'color': 'red', 'points': 12, 'speed': 'slow'}]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值