python数据类型-4-容器类型-字典(字典的深拷贝和JSON转换)
一.说明
在python数据类型系列文章中已经介绍了 基础数据类型,容器类型 列表,元组等,今天我们来一起学习字典这一类型,
二.Dictionary(字典)
1.定义
1.字典是用于存储键值对的数据结构;
2.字典的键必须唯一;
3.字典是一个可变的、无序的集合;
4.字典的值可以是任意数据类型,甚至字典;
5.字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中;
2.特性
1.无序性:字典的键值对没有特定的顺序(在 Python 3.7 及以后的版本中,插入顺序会被保持,但不保证有序性);
2.键唯一性:字典中的键必须是唯一的。如果添加一个已经存在的键,将会覆盖原有的值;
3.可变性:字典是可变的,你可以随时添加、删除或修改字典中的键值对;
4.快速查找:字典支持高效的查找操作,通常情况下其查找时间复杂度为 O(1)。
3.创建字典
1.使用大括号 {}
# 创建一个字典
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
2.使用 dict()
函数
# 使用 dict() 创建字典
my_dict = dict(name="Alice", age=30, city="New York")
3.使用键值对列表
# 使用列表创建字典
my_dict = dict([("name", "Alice"), ("age", 30), ("city", "New York")])
4.使用字典推导式(Dictionary Comprehension)
# 字典推导式
my_dict = {x: x**2 for x in range(5)}
# 结果: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
这里有个隐藏知识点,就是字典的键唯一性?那么针对这一特性能用在什么场景呢?
这就是涉及 快速去重的一个方法,当然还有很多应用场景基本不看也明白,这里重点说明下利用字典这一特性实现去重?
# 原始列表
items = ["apple", "banana", "apple", "orange", "banana"]
# 使用 dict.fromkeys() 去重
unique_items = list(dict.fromkeys(items))
print(unique_items) # 输出: ['apple', 'banana', 'orange']
#复杂列表去重
# 原始列表
items = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Alice", "age": 35}, # 重复的名字
{"name": "Charlie", "age": 20}
]
# 使用字典去重(根据名字)
unique_items = {item["name"]: item for item in items}.values()
print(list(unique_items))
# 输出: [{'name': 'Alice', 'age': 35}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 20}]
# 原始列表
items = [
("apple", 1),
("banana", 2),
("apple", 1), # 重复的元组
("orange", 3)
]
# 使用 dict 去重
unique_items = list(dict.fromkeys(items))
print(unique_items)
# 输出: [('apple', 1), ('banana', 2), ('orange', 3)]
# 原始列表
items = [
["apple", 1],
["banana", 2],
["apple", 1], # 重复的子列表
["orange", 3]
]
# 使用字典去重(将子列表转换为元组)
unique_items = list({tuple(item): item for item in items}.values())
print(unique_items)
# 输出: [['apple', 1], ['banana', 2], ['orange', 3]]
通过适当地选择键和处理数据结构,我们可以有效地对复杂列表进行去重,字典的唯一性特性在许多情况下都能帮助我们简化并且快速实现去重操作。
4.常用的操作和方法
1.访问字典中的值
这里要注意的是,当访问的键不存在时,报错,那么如何避免?
就是,使用 get()
方法访问值
my_dict = {"name": "Alice", "age": 30}
print(my_dict["name"]) # 输出: Alice
print(my_dict["name12"]) # 报错
# 使用 `get()` 方法访问值
print(my_dict.get("age", "Not found")) # 输出: 30
print(my_dict.get("name12", "Not found")) # 输出: Not found
2.添加和更新键值对
my_dict = {"name": "Alice", "age": 30}
# 添加新键值对
my_dict["email"] = "alice@example.com"
# 更新已有键值对
my_dict["age"] = 31
4.删除键值对
# 使用 del 删除
del my_dict["age"]
# 使用 pop() 删除并返回值
email = my_dict.pop("email") # 返回 "alice@example.com"
5.遍历字典
# 遍历键
for item in my_dict:
print(item)
# 遍历键
for key in my_dict.keys():
print(key)
# 遍历值
for value in my_dict.values():
print(value)
# 遍历键值对
for key, value in my_dict.items():
print(key, value)
5.字典的方法
1.keys()
:返回字典中所有的键
keys = my_dict.keys() # 返回一个可迭代的字典视图
2.values()
:返回字典中所有的值
values = my_dict.values() # 返回一个可迭代的字典视图
3.items()
:返回字典中所有的键值对。
items = my_dict.items() # 返回一个可迭代的字典视图
4.clear()
:清空字典。
my_dict.clear() # my_dict 现在是 {}
5.copy()
:返回字典的浅拷贝。
copy_dict = my_dict.copy()
6.popitem()
:随机弹出并返回一个键值对,通常是最后插入的键值对。
item = my_dict.popitem() # 返回一个元组 (key, value)
7.update()
:合并另一个字典,更新现有的键值对。
my_dict = {"name": "Alice", "age": 30}
my_dict.update({"age": 31, "city": "New York"})
print(my_dict) #{'name': 'Alice', 'age': 31, 'city': 'New York'}
#另外一个合并方法
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
# 合并字典,后面的字典会覆盖前面的字典中的相同键
merged_dict = {**dict1, **dict2}
print(merged_dict) # 输出: {'a': 1, 'b': 3, 'c': 4}
这里有个隐藏知识点,我来给大家标出来,就是字典的深拷贝!我们在真实项目中 使用的通常是深拷贝
import copy
# 创建一个复杂字典
original_dict = {
"name": "Alice",
"age": 30,
"hobbies": ["reading", "hiking"],
"address": {
"city": "New York",
"zip": "10001"
},
"friends": [
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 28}
]
}
# 使用 deepcopy() 进行深拷贝
copied_dict = copy.deepcopy(original_dict)
# 输出原始字典和拷贝的字典
print("Original Dictionary:")
print(original_dict)
print("Copied Dictionary:")
print(copied_dict)
# 修改原始字典,看看拷贝是否受到影响
original_dict["hobbies"].append("coding")
original_dict["address"]["city"] = "Los Angeles"
original_dict["friends"][0]["age"] = 26
print("\nAfter Modifications:")
print("Original Dictionary:")
print(original_dict)
print("\nCopied Dictionary (should remain unchanged):")
print(copied_dict)
'''
运行上述代码后,输出结果将类似于以下内容:
Original Dictionary:
{'name': 'Alice', 'age': 30, 'hobbies': ['reading', 'hiking'], 'address': {'city': 'New York', 'zip': '10001'}, 'friends': [{'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 28}]}
Copied Dictionary:
{'name': 'Alice', 'age': 30, 'hobbies': ['reading', 'hiking'], 'address': {'city': 'New York', 'zip': '10001'}, 'friends': [{'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 28}]}
After Modifications:
Original Dictionary:
{'name': 'Alice', 'age': 30, 'hobbies': ['reading', 'hiking', 'coding'], 'address': {'city': 'Los Angeles', 'zip': '10001'}, 'friends': [{'name': 'Bob', 'age': 26}, {'name': 'Charlie', 'age': 28}]}
Copied Dictionary (should remain unchanged):
{'name': 'Alice', 'age': 30, 'hobbies': ['reading', 'hiking'], 'address': {'city': 'New York', 'zip': '10001'}, 'friends': [{'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 28}]}
'''
6.字典的JSON处理
1.字典转JSON
字典在处理 JSON 数据时非常方便,因为 JSON 对象与 Python 字典非常相似
在 Python 中,将字典转换为 JSON 格式通常使用 json
模块
import json
# 创建一个字典
data = {
"name": "Alice",
"age": 30,
"hobbies": ["reading", "hiking"],
"address": {
"city": "New York",
"zip": "10001"
}
}
# 将字典转换为 JSON 字符串
json_data = json.dumps(data, indent=4) # indent 参数用于美化输出
print(json_data)
2.json转字典
将 JSON 转换为字典可以使用 Python 的 json
模块中的 loads()
方法
import json
# JSON 字符串
json_data = '''
{
"name": "Alice",
"age": 30,
"hobbies": ["reading", "hiking"],
"address": {
"city": "New York",
"zip": "10001"
}
}
'''
# 将 JSON 字符串转换为字典
data_dict = json.loads(json_data)
# 输出字典
print(data_dict)
3.错误处理
try:
data_dict = json.loads(json_data)
except json.JSONDecodeError as e:
print(f"JSON 解码错误: {e}")
三.总结
python中字典使用实在是太频繁了,这里划重点 字典的深拷贝 字典的JSON互相转换!,针对字典,我就写到这,有不足地方,欢迎大家补充,我来更新!
创作不易,喜欢的话点点关注 点点赞,再次_感谢!