EasyDict:让字典操作更简单
在 Python 中,字典(dict
)是一种非常常用的数据结构,用于存储键值对。然而,访问字典中的值时,通常需要使用 dict['key']
的语法,这在某些情况下可能会显得不够直观或方便。
EasyDict
是一个轻量级的 Python 库,它允许你以属性的方式访问字典中的值,从而让代码更加简洁和易读。
安装
pip install easydict
基本用法
EasyDict的核心用法非常简单,流程如下:
导入EasyDict,使用
from easydict import EasyDict
初始化EasyDict对象,将dict数据放进形参中
将原始字典的值当属性被EasyDict对象调用即可
这里展示一下基本用法
from easydict import EasyDict
# 创建一个字典
data = {
'name': 'Alice',
'age': 25,
'address': {
'city': 'Wonderland',
'zipcode': '12345'
}
}
# 将字典转换为 EasyDict
ed = EasyDict(data)
# 访问属性
print(ed.name) # 输出: Alice
print(ed.age) # 输出: 25
print(ed.address.city) # 输出: Wonderland
# 修改属性
ed.age = 26
print(ed.age) # 输出: 26
# 添加新属性
ed.gender = 'Female'
print(ed.gender) # 输出: Female
注意:原始字典的key值不能为数字,即:
data = {
'1': 'Alice',
'2': 25,
'3': {
'city': 'Wonderland',
'zipcode': '12345'
}
} # 这种dict是不能被EasyDict初始化的
这种类型的字典如果被EasyDict初始化后,将无法作为属性调用
嵌套
EasyDict
支持在字典中嵌套列表、元组、字典、甚至是对象
在嵌套中甚至还可以嵌套,而EasyDict
能用很方便的方式去调用它
首先我们构建一个复杂嵌套结构的字典
import numpy as np
# 创建一个复杂嵌套结构的字典
data = {
"name": "Data Analysis",
"tags": ["Python", "Machine Learning", "AI"], # 嵌套列表
"metadata": {
"author": "Bob",
"date": "2023-10-01",
"version": (1, 0, 0) # 嵌套元组
},
"matrix": np.array([[1, 2], [3, 4]]), # 嵌套 numpy 数组
"dataset": {
"features": np.random.randn(3, 2), # 嵌套字典中的 numpy 数组
"labels": np.array([0, 1, 0])
}
}
而后我们转换成EasyDict
对象
from easydict import EasyDict
# 转换为 EasyDict 对象
ed = EasyDict(data)
后面我们可以通过EasyDict
对象来访问这些嵌套的数据了
访问嵌套列表
在访问嵌套列表时,我们可以通过下标的方式访问列表中的某个元素(就像平常使用列表一样)
print("Tags:", ed.tags) # 输出: ['Python', 'Machine Learning', 'AI']
print("First tag:", ed.tags[0]) # 输出: Python
访问嵌套元组
访问嵌套元组时和列表基本一致
print("Metadata version:", ed.metadata.version) # 输出: (1, 0, 0)
print("Major version:", ed.metadata.version[0]) # 输出: 1
访问嵌套的对象
访问嵌套的对象时,直接使用属性访问即可。访问后可以直接使用对象的方法。
假设用numpy,我们访问该numpy对象后,可以直接调用该对象的方法sum
。
# 访问嵌套的 numpy 数组
print("Matrix:")
print(ed.matrix)
print(ed.matrix.sum()) # 调用numpy对象中的方法sum
# 输出:
# [[1 2]
# [3 4]]
当然可以修改该对象的某些值或者属性
# 修改嵌套的 numpy 对象
ed.matrix[0, 1] = 99 # 修改矩阵中的元素
print("Modified Matrix:")
print(ed.matrix)
# 输出:
# [[ 1 99]
# [ 3 4]]
访问嵌套字典中嵌套的numpy数组
原字典中的嵌套字典,在转换成EasyDict
后,嵌套字典也会自动转换成EasyDict
对象,这个嵌套的字典也可以嵌套对象。
这些嵌套的内容直接用属性访问即可:
# 访问嵌套字典中的 numpy 数组
print("Dataset features:")
print(ed.dataset.features)
# 输出示例:
# [[-0.23 1.45]
# [ 0.67 -1.12]
# [ 1.89 -0.34]]
嵌套的嵌套也可以进行修改:
# 修改嵌套的 numpy 对象
ed.dataset.features[1, 0] = 5.0 # 修改特征数组
print("Modified Dataset Features:")
print(ed.dataset.features)
# 输出示例:
# [[-0.23 1.45]
# [ 5.0 -1.12]
# [ 1.89 -0.34]]
输出items
EasyDict
可以很轻易得输出key
、values
和items
,只需要调用其中的一个方法即可。
其输出为dict_items
,如果有需要则可以将其转换成list:
from easydict import EasyDict
# 创建一个 EasyDict 对象
ed = EasyDict({
"name": "Alice",
"age": 25,
"address": {
"city": "Wonderland",
"zipcode": "12345"
},
"hobbies": ["reading", "traveling", "coding"]
})
# 使用 items() 方法获取键值对
print("Items:")
for key, value in ed.items():
print(f"{key}: {value}")
# 输出:
# name: Alice
# age: 25
# address: {'city': 'Wonderland', 'zipcode': '12345'}
# hobbies: ['reading', 'traveling', 'coding']
# 使用 keys() 方法获取所有键
print("Keys:")
for key in ed.keys():
print(key)
# 输出:
# name
# age
# address
# hobbies
# 使用 values() 方法获取所有值
print("Values:")
for value in ed.values():
print(value)
# 输出:
# Alice
# 25
# {'city': 'Wonderland', 'zipcode': '12345'}
# ['reading', 'traveling', 'coding']
# 修改 EasyDict 的内容
ed.age = 26
ed.hobbies.append("painting")
# 再次查看修改后的 items()
print("Modified Items:")
for key, value in ed.items():
print(f"{key}: {value}")
# 输出:
# name: Alice
# age: 26
# address: {'city': 'Wonderland', 'zipcode': '12345'}
# hobbies: ['reading', 'traveling', 'coding', 'painting']
字典合并与链式操作
EasyDict
支持通过 update()
方法合并字典。与普通字典的 update()
方法类似,它会将另一个字典的键值对添加到当前字典中。如果键已经存在,则覆盖原有的值。
from easydict import EasyDict
# 创建两个 EasyDict 对象
ed1 = EasyDict({"name": "Alice", "age": 25})
ed2 = EasyDict({"age": 26, "city": "Wonderland"})
# 合并字典
ed1.update(ed2)
print(ed1)
# 输出: {'name': 'Alice', 'age': 26, 'city': 'Wonderland'}
每个 update()
方法都返回 EasyDict
对象本身,这意味着你可以在一个语句中连续调用多个update()
方法,例如:
from easydict import EasyDict
# 创建多个字典
data1 = {"name": "Alice"}
data2 = {"age": 25}
data3 = {"city": "Wonderland"}
# 链式合并多个字典
ed = EasyDict().update(data1).update(data2).update(data3)
print(ed)
# 输出: {'name': 'Alice', 'age': 25, 'city': 'Wonderland'}
嵌套字典的合并
EasyDict
还支持嵌套字典的合并。如果合并的字典中有嵌套结构,EasyDict
会自动处理嵌套部分的合并。
from easydict import EasyDict
# 创建嵌套字典
ed1 = EasyDict({
"name": "Alice",
"address": {
"city": "Wonderland",
"zipcode": "12345"
}
})
ed2 = EasyDict({
"age": 25,
"address": {
"zipcode": "67890",
"country": "Fantasy"
}
})
# 合并嵌套字典
ed1.update(ed2)
print(ed1)
# 输出:
# {
# 'name': 'Alice',
# 'age': 25,
# 'address': {
# 'city': 'Wonderland',
# 'zipcode': '67890',
# 'country': 'Fantasy'
# }
# }