EasyDict使用

EasyDict allows to access dict values as attributes (works recursively). A Javascript-like properties dot notation for python dicts.

USAGE

>>> from easydict import EasyDict as edict
>>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}})
>>> d.foo
3
>>> d.bar.x
1

>>> d = edict(foo=3)
>>> d.foo
3

Very useful when exploiting parsed JSON content !

>>> from easydict import EasyDict as edict
>>> from simplejson import loads
>>> j = """{
"Buffer": 12,
"List1": [
    {"type" : "point", "coordinates" : [100.1,54.9] },
    {"type" : "point", "coordinates" : [109.4,65.1] },
    {"type" : "point", "coordinates" : [115.2,80.2] },
    {"type" : "point", "coordinates" : [150.9,97.8] }
]
}"""
>>> d = edict(loads(j))
>>> d.Buffer
12
>>> d.List1[0].coordinates[1]
54.9

Can set attributes as easily as getting them :

>>> d = EasyDict()
>>> d.foo = 3
>>> d.foo
3

It is still a dict !

>>> d = EasyDict(log=False)
>>> d.debug = True
>>> d.items()
[('debug', True), ('log', False)]

Instance and class attributes are accessed like usual objects…

>>> class Flower(EasyDict):
...     power = 1
...
>>> f = Flower({'height': 12})
>>> f.power
1
>>> f['power']
1
### EasyDict 的用法与相关信息 `EasyDict` 是一个 Python 第三方库,它允许开发者通过点号(`.`)访问字典中的键值对,类似于对象属性的访问方式。这种设计使得代码更加简洁和直观[^5]。以下是关于 `EasyDict` 的详细说明和使用示例: #### 1. 安装 `EasyDict` 可以通过 `pip` 工具轻松安装。在命令行中运行以下命令即可完成安装: ```bash pip install easydict ``` #### 2. 基本用法 创建一个 `EasyDict` 对象后,可以通过点号访问字典中的键值对。例如: ```python from easydict import EasyDict as edict config = edict() config.a = 1 config.b = 2 config.c = edict({'x': 3, 'y': 4}) print(config.a) # 输出: 1 print(config.c.x) # 输出: 3 ``` #### 3. 从普通字典转换 如果已经有一个普通的字典,可以将其直接传递给 `EasyDict` 构造函数进行转换: ```python from easydict import EasyDict as edict normal_dict = {'a': 1, 'b': {'c': 2, 'd': 3}} easy_dict = edict(normal_dict) print(easy_dict.a) # 输出: 1 print(easy_dict.b.c) # 输出: 2 ``` #### 4. 支持嵌套结构 `EasyDict` 支持嵌套结构,并且可以递归地将嵌套字典转换为 `EasyDict` 对象[^6]: ```python from easydict import EasyDict as edict nested_dict = { 'level1': { 'level2': { 'value': 42 } } } easy_nested_dict = edict(nested_dict) print(easy_nested_dict.level1.level2.value) # 输出: 42 ``` #### 5. 修改与添加 `EasyDict` 允许像操作普通对象一样修改或添加新的属性: ```python from easydict import EasyDict as edict config = edict() config.new_key = "new_value" config.existing_key = "updated_value" print(config.new_key) # 输出: new_value print(config.existing_key) # 输出: updated_value ``` #### 6. 转换回普通字典 如果需要将 `EasyDict` 转换回普通字典,可以使用内置的 `dict()` 函数: ```python from easydict import EasyDict as edict config = edict({'a': 1, 'b': {'c': 2}}) normal_dict = dict(config) print(normal_dict['b']['c']) # 输出: 2 ``` ### 注意事项 - `EasyDict` 并不会改变原始字典的行为,只是提供了一种更方便的访问方式。 - 如果字典中的键名不符合合法的 Python 标识符规则(如包含空格或特殊字符),仍然需要使用方括号访问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值