当我们需要在 Python 中存储和访问键值对数据时,最好使用字典。在下面的代码示例中,我将介绍 Python 字典的各种用法和实例。
创建字典
可以使用花括号 {} 或 dict() 函数来创建一个空字典。下面的代码示例演示如何创建字典:
# 创建空字典
empty_dict = {
}
print(empty_dict)
# 使用字面量创建字典
person_dict = {
"name": "Alice", "age": 25, "city": "New York"}
print(person_dict)
# 使用 dict() 函数创建字典
fruit_dict = dict(apple=3, banana=2, cherry=5)
print(fruit_dict)
访问字典元素
可以通过键来访问字典中的元素。如果键不存在,Python 将引发 KeyError 异常。下面的代码示例演示如何访问字典元素:
person_dict = {
"name": "Alice", "age": 25, "city": "New York"}
# 通过键访问字典元素
print(person_dict["name"])
print(person_dict["age"])
print(person_dict["city"])
# 尝试访问不存在的键会引发 KeyError 异常
# print(person_dict["gender"])
添加和更新字典元素
可以使用赋值运算符或 update() 方法向字典中添加或更新元素。如果键不存在,将添加新元素;如果键已经存在,将更新现有值。下面的代码示例演示如何添加和更新字典元素:
fruit_dict = {
"apple": 3, "banana": 2, "cherry": 5}
# 添加新元素
fruit_dict["orange"] = 4
print(fruit_dict)
# 更新现有值
fruit_dict["banana"] = 7
print(fruit_dict)
# 使用 update() 方法添加多个元素
fruit_dict.update({
"pear": 6, "kiwi": 8})
print(fruit_dict)
删除字典元素
可以使用 del 关键字或 pop() 方法从字典中删除元素。如果键不存在,将引发 KeyError 异常。下面的代码示例演示如何删除字典元素:
fruit_dict = {
"apple": 3, "banana": 2, "cherry": 5}
# 删除指定键的元素
del fruit_dict["banana"]
print(fruit_dict)
# 使用 pop() 方法删除指定键的元素
fruit_dict.pop("cherry")
print(fruit_dict)
# 尝试删除不存在的键会引发 KeyError 异常
# del fruit_dict["orange"]
# fruit_dict.pop("orange")
字典遍历
可以使用 for 循环遍历字典中的键、值或键值对。下面的代码示例演示如何遍历字典:
fruit_dict = {
"apple": 3, "banana": 2, "cherry": 5}
# 遍历键
for key in fruit_dict:
print(key)
# 遍历值
for value in fruit_dict.values():
print(value)
# 遍历键值对
for key, value in fruit_dict.items():
print(key, value)
字典推导式
可以使用字典推导式来创建新字典,该字典基于现有字典的筛选或转换。下面的代码示例演示如何使用字典推导式:
fruit_dict = {
"apple": 3, "banana": 2, "cherry": 5}
# 筛选出数量大于 3 的水果
filtered_dict = {
"apple": 3,
key: value for key, value in fruit_dict.items() if value > 3}
print(filtered_dict)
# 将所有水果数量乘以 2
multiplied_dict = {
key: value * 2 for key, value in fruit_dict.items()}
print(multiplied_dict)
Python中的字典(dictionary)是一种非常常用的数据结构,它可以存储一系列的键值对,其中每个键都是唯一的。字典是一种可变的数据类型,可以动态地添加、删除和修改键值对。以下是Python字典的一些高阶用法:
字典的键值对交换
可以使用以下方法交换字典的键和值:
my_dict = {
'apple': 1, 'banana': 2, 'orange': 3}
new_dict ={
value: key for key, value in my_dict.items()}
print(new_dict)
# 输出:{1: 'apple', 2: 'banana', 3: 'orange'}
字典的排序
字典本身是没有顺序的,但是可以通过以下方法对字典的键或值进行排序:
# 按照键排序
my_dict = {
'apple': 1, 'banana': 2, 'orange': 3}
sorted_dict = {
key: my_dict[key] for key in sorted(my_dict)}
print(sorted_dict)
# 输出:{'apple': 1, 'banana': 2, 'orange': 3}
# 按照值排序
my_dict = {
'apple': 1, 'banana': 2, 'orange': 3}
sorted_dict = {
key: value for key, value in sorted(my_dict.items(), key=lambda item: item[1])}
print(sorted_dict)
# 输出:{'apple': 1, 'banana': 2, 'orange': 3}
字典的合并
可以使用update()方法将一个字典合并到另一个字典中:
dict1 = {
'apple': 1, 'banana': 2}
dict2 = {
'orange': 3, 'pear': 4}
dict1.update(dict2)
print(dict1)
# 输出:{'apple': 1, 'banana': 2, 'orange': 3, 'pear': 4}
字典的过滤
可以使用以下方法对字典进行过滤,只保留符合条件的键值对:
my_dict = {
'apple': 1, 'banana': 2, 'orange': 3}
filtered_dict = {
key: value for key, value in my_dict.items() if value > 1}
print(filtered_dict)
# 输出:{'banana': 2, 'orange': 3}
字典的默认值
如果字典中不存在某个键,可以使用以下方法设置一个默认值:
my_dict = {
'apple': 1, 'banana': 2}
print(my_dict.get('orange', 0))
# 输出:0
以上是Python字典的一些高阶用法。字典是一种非常方便的数据结构,在Python中被广泛应用。掌握了以上高阶用法,可以更加高效地使用字典,并在实际开发中发挥更大的作用。
以上是 Python 字典的基本用法和示例。希望这些例子能帮助您更好地了解 Python 字典的使用方法。