Python 字典
提示
- 字典的创建和访问:Python 字典通过键值对存储数据,可通过
{键: 值}
的形式创建,并通过键来访问相应的值。 - 修改和添加字典项:字典是可变的,可以通过指定的键更改其值或向字典添加新的键值对。
- 字典操作和遍历:提供了多种方法如 pop(), update(), keys() 等来操作字典,并可使用 for 循环来遍历字典的键或值。
在 Python 中,字典是一种集合,它允许我们以键值对的形式存储数据。
创建字典
我们通过将键:值对放置在花括号 {}
中并用逗号分隔来创建字典。例如,
# 创建一个字典
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}
# 打印字典
print(country_capitals)
输出
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'England': 'London'}
country_capitals
字典有三个元素(键值对)。
注意:字典键必须是不可变的,例如元组、字符串、整数等。我们不能使用可变(可改变的)对象,如列表作为键。
# 有效的字典
my_dict = {
1: "Hello",
(1, 2): "Hello Hi",
3: [1, 2, 3]
}
print(my_dict)
# 无效的字典
# 错误:使用列表作为键是不允许的
my_dict = {
1: "Hello",
[1, 2]: "Hello Hi",
}
print(my_dict)
提示:我们也可以使用 Python 的 dict() 函数来创建字典。
Python 字典长度
我们可以使用 len() 函数获取字典的大小。
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}
# 获取字典的长度
print(len(country_capitals)) # 3
访问字典项
我们可以通过将键放置在方括号内来访问字典项的值 。
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}
print(country_capitals["United States"]) # Washington D.C.
print(country_capitals["England"]) # London
注意:我们也可以使用 get() 方法 来访问字典项。
更改字典项
Python 字典是可变的(可改变的)。我们可以通过引用其键来更改字典元素的值。例如,
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples",
"England": "London"
}
# 更改 "Italy" 键的值为 "Rome"
country_capitals["Italy"] = "Rome"
print(country_capitals)
输出
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'England': 'London'}
向字典添加项
我们可以通过为新键(在字典中不存在的键)赋值来向字典添加项。例如,
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}
# 添加一个键为 "Germany"、值为 "Berlin" 的项
country_capitals["Germany"] = "Berlin"
print(country_capitals)
输出
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'Germany': 'Berlin'}
注意:我们还可以使用 update 方法() 来添加或更改字典项。
移除字典项
我们使用 del
语句从字典中移除元素。例如,
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}
# 删除键为 "United States" 的项
del country_capitals["United States"]
print(country_capitals)
输出
{'Italy': 'Naples'}
注意:我们也可以使用 pop 方法() 从字典中移除项。
如果我们需要一次
移除字典中的所有项,我们可以使用 clear()
方法。
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}
country_capitals.clear()
print(country_capitals) # {}