Python学习之路5-字典
《Python编程:从入门到实践》笔记。
本章主要介绍字典的概念,基本操作以及一些进阶操作。
1. 使用字典(Dict)
在Python中,字典是一系列键值对。每个键都与一个值相关联,用键来访问值。Python中用花括号{}来表示字典。
# 代码:
alien = {"color": "green", "points": 5}
print(alien) # 输出字典
print(alien["color"]) # 输出键所对应的值
print(alien["points"])
# 结果:
{'color': 'green', 'points': 5}
green
5字典中可以包含任意数量的键值对,并且Python中字典是一个动态结构,可随时向其中添加键值对。
# 代码:
alien = {"color": "green", "points": 5}
print(alien)
alien["x_position"] = 0
alien["y_position"] = 25
print(alien)
# 结果:
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}有时候,在空字典中添加键值对是为了方便,而有时候则是必须这么做,比如使用字典来存储用户提供的数据或在编写能自动生成大量键值对的代码时,此时通常要先定义一个空字典。
# 代码:
alien = {} # 定义空字典的语法
alien["x_position"] = 0
alien["y_position"] = 25
print(alien)
# 结果:
{'x_position': 0, 'y_position': 25}如果要修改字典中的值,只需通过键名访问就行。
# 代码:
alien = {"color" : "green"}
print("The alien is " + alien["color"] + ".")
alien["color"] = "yellow"
print("The alien is now " + alien["color"] + ".")
# 结果:
The alien is green.
The alien is now yellow.对于字典中不再需要的信息,可用del语句将相应的键值对删除:
# 代码:
alien = {"color": "green", "points": 5}
print(alien)
del alien["color"]
print(alien)
# 结果:
{'color': 'green', 'points': 5}
{'points': 5}前面的例子都是一个对象的多种信息构成了一个字典(游戏中的外星人信息),字典也可以用来存储众多对象的统一信息:
favorite_languages = {
"jen": "python",
"sarah": "c",
"edward": "ruby",
"phil": "python", # 建议在最后一项后面也加个逗号,便于之后添加元素
}2. 遍历字典
2.1 遍历所有的键值对
# 代码:
user_0 = {
"username": "efermi",
"first": "enrico",
"last": "fermi",
}
for key, value in user_0.items():
print("Key: " + key)
print("Value: " + value + "\n")
# 结果:
Key: username
Value: efermi
Key: first
Value: enrico
Key: last
Value: fermi这里有一点需要注意,遍历字典时,键值对的返回顺序不一定与存储顺序相同,Python不关心键值对的存储顺序,而只追踪键与值之间的关联关系。
2.2 遍历字典中的所有键
字典的方法keys()将字典中的所有键以列表的形式返回,以下代码遍历字典中的所有键:
# 代码:
favorite_languages = {
"jen": "python",
"sarah": "c",
"edward": "ruby",
"phil": "python",
}
for name in favorite_languages.keys():
print(name.title())
# 结果:
Jen
Sarah
Edward
Phil也可以用如下方法遍历字典的所有键:
# 代码:
favorite_languages = {
"jen": "python",
"sarah": "c",
"edward": "ruby",
"phil": "python",
}
for name in favorite_languages:
print(name.title())
# 结果:
Jen
Sarah
Edward
Phil但是带有方法keys()的遍历所表达的意思更明确。
还可以用keys()方法确定某关键字是否在字典中:
# 代码:
favorite_languages = {
"jen": "python",
"sarah": "c",
"edward": "ruby",
"phil": "python",
}
if "erin" not in favorite_languages.keys():
print("Erin, please take our poll!")
# 结果:
Erin, please take our poll!使用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.2.3 遍历字典中的所有值
类似于遍历所有键用keys()方法,遍历所有值则使用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())
# 结果:
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())
# 结果:
Python
C
Ruby3. 嵌套
3.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}3.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 pizzawith the following toppings:
mushrooms
extra cheese3.3 在字典中存储字典
涉及到这种情况时,代码都不会简单:
# 代码:
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迎大家关注我的微信公众号"代码港" & 个人网站 www.vpointer.net ~
