《Python编程:从入门到实践》学习笔记——字典

一、字典

1.字典介绍

在Python中,字典是一系列键值对,每个键都与一个值相关联,与键相关联的值可以是数字、字符串、列表或者字典,即可将任何Python对象用作字典中的值。字典中的元素放在花括号{}中,键和值之间用冒号分隔,键值对之间用逗号分隔。

2.访问字典中的值

要获取与键相关联的值,可依次指定字典名和放在方括号内的键。比如:

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

结果如下:

green

3.添加键值对

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

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, 'x_position': 0, 'y_position': 25}

注:有时候必须在空字典中添加键值对,可先使用一对空的花括号定义一个字典,再分行添加各个键值对。

4.修改字典中的值

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

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
print("New x-position: " + str(alien_0['x_position']))

结果如下:

Original x-position: 0
New x-position: 2

5.删除键值对

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

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

del alien_0['points']
print(alien_0)

结果如下:

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

6.由类似对象组成的字典

字典可以存储众多对象的同一种信息。确定需要使用多行来定义字典时,在输入左花括号后按回车键,再在下一行缩进四个空格,指定第一个键值对,并在其后加上一个逗号,之后再次按回车键时,文本编辑器会自动缩进后续键值对,且缩进量与第一个键值对相同,最后,在最后一个键值对的下一行添加一个右花括号,并缩进四个空格,使其与字典中的键对齐。比如:

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

结果如下:

Sarah's favorite language is C.

注:这个示例还演示了如何将较长的print语句分成多行。请选择在合适的地方拆分要打印的内容,并在第一行末尾加上一个拼接运算符(+),按回车键进入print语句的后续各行,并使用Tab键将它们对齐并缩进一级,指定要打印的所有内容后,在print语句的最后一行末尾加上括号。

二、遍历字典

1.遍历所有的键值对

用for循环和方法items()遍历字典,它返回一个键值对列表,for循环依次将每个键值对存储到指定的两个变量中。比如:

user_0 = {
	'username': 'efermi',
	'first': 'enrico',
	'last': 'feimi',
	}

for key, value in user_0.items():
	print("\nKey: " + key)
	print("Value: " + value)

结果如下:


Key: username
Value: efermi

Key: first
Value: enrico

Key: last
Value: feimi

2.遍历字典中的所有键

A

在不需要使用字典中的值时,使用方法keys()遍历字典中的所有键。比如:

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

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

结果如下:

Jen
Sarah
Edward
Phil

注:for name in favorite_languages.keys():等同于for name in favorite_languages:。

B.按顺序遍历字典中的所有键

要按特定顺序返回元素,可以在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.

3.遍历字典中的所有值

使用方法values()。它返回一个值列表,不包含任何键。比如:

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

print("The following languages have been mentioned:")
for language in favorite_languages.values():
	print(language.title())

结果如下:

The following languages have been mentioned:
Python
C
Ruby
Python

注:为剔除重复项,可使用集合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:
Ruby
C
Python

三、嵌套

将一系列字典存储在列表中,或将列表作为值存储在字典中,称为嵌套

1.字典列表

列表中的元素是字典。比如:

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}

2.在字典中存储列表

比如:

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

3.在字典中存储字典

比如:

users = {
	'aeinstein': {
		'first': 'albert',
		'last': 'aeinstein',
		'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 Aeinstein
        location: Princeton

Username: mcurie
        Full name: Marie Curie
        location: Paris
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值