python 又一个点运算符操作的字典库:Munch

简介: python 又一个点运算符操作的字典库:Munch

munch

又一个将字典(dict)变成类似对象(object)的库。这意味着你可以使用点符号(.)而不是方括号([])来访问字典的键。这使得代码更易读,尤其是在处理嵌套字典时。

相关阅读:python 一个点运算符操作的字典库:DottedDict-CSDN博客

安装

首先,你需要安装 munch 库。你可以使用 pip 来安装它:

pip install munch

使用

1. 创建空对象
from munch import Munch
 
# 创建一个空的Munch对象
data = Munch()
 
# 添加键值对
data.name = 'Hann'
data.age = 50
2. 创建于字典
from munch import Munch
 
# 创建一个Munch对象
data = Munch({'name': 'Hann', 'age': 51})
 
# 使用点符号访问属性
print(data.name)  # 输出: Hann
print(data.age)   # 输出: 51
 
# 修改属性
data.age = 50
print(data.age)   # 输出: 50
 
# 添加新属性
data.height = 172
print(data.height)  # 输出: 172
3. 嵌套字典方法 .fromDict()

嵌套字典必须用此方法,不能直接用Munch()

from munch import Munch
 
data = Munch.fromDict({'user':{"name": "Hann", "age": 50}})
print(data.user.name)  # 输出:Hann
print(data.user.age)   # 输出:50

特点

  • 点符号访问:使用点符号来访问和设置键的值,使代码更加直观。
  • 动态属性:可以动态地添加新的键。
  • 保持字典特性Munch 对象仍然保持了字典的所有特性,如使用 .keys(), .values(), .items() 等方法。
  • 转换回字典:可以很容易地将 Munch 对象转换回普通的字典。

应用场景

munch 库特别适合于以下场景:

  • 配置文件:处理配置信息时,使用点符号比索引数组更清晰。
  • 数据模型:在创建数据模型时,可以更方便地访问和修改嵌套的数据。
  • JSON解析:处理 JSON 数据时,Munch 提供了一种更人性化的访问方式。

注意事项

  • 性能:由于 munch 增加了额外的层,它可能比直接使用字典慢一些,尤其是在处理大量数据时。
  • 调试:使用点符号可能会让某些调试器的智能提示功能失效,因为它们可能不识别 Munch 对象的动态属性。

结论

munch 是一个简单而有用的库,可以提高处理字典数据时的代码可读性和便利性。尽管它在性能上可能有所牺牲,但在很多应用场景下,这种牺牲是值得的。如果你经常需要处理嵌套的字典数据,munch 库是一个值得考虑的选择。

希望这篇文章能帮助你更好地了解 munch 库以及如何在你的 Python 项目中使用它。如果你有任何问题或想要了解更多关于 munch 的信息,请随时提问。

附录

英文帮助(节选)
munch - Munch is a subclass of dict with attribute-style access.

DESCRIPTION
    >>> b = Munch()
    >>> b.hello = 'world'
    >>> b.hello
    'world'
    >>> b['hello'] += "!"
    >>> b.hello
    'world!'
    >>> b.foo = Munch(lol=True)
    >>> b.foo.lol
    True
    >>> b.foo is b['foo']
    True

    It is safe to import * from this module:

        __all__ = ('Munch', 'munchify','unmunchify')

    un/munchify provide dictionary conversion; Munches can also be
    converted via Munch.to/fromDict().


A Munch that calls a user-specified function to generate values for
missing keys like collections.defaultdict.

>>> b = DefaultFactoryMunch(list, {'hello': 'world!'})
>>> b.hello
'world!'
>>> b.foo
[]
>>> b.bar.append('hello')
>>> b.bar
['hello']

__init__(self, default_factory, *args, **kwargs)
    Initialize self.  See help(type(self)) for accurate signature.

__missing__(self, k)

__repr__(self)
    Invertible* string-form of a Munch.

    >>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
    >>> print (repr(b))
    Munch({'ponies': 'are pretty!', 'foo': Munch({'lol': True}), 'hello': 42})
    >>> eval(repr(b))
    Munch({'ponies': 'are pretty!', 'foo': Munch({'lol': True}), 'hello': 42})

    >>> with_spaces = Munch({1: 2, 'a b': 9, 'c': Munch({'simple': 5})})
    >>> print (repr(with_spaces))
    Munch({'a b': 9, 1: 2, 'c': Munch({'simple': 5})})
    >>> eval(repr(with_spaces))
    Munch({'a b': 9, 1: 2, 'c': Munch({'simple': 5})})

    (*) Invertible so long as collection contents are each repr-invertible.

__setattr__(self, k, v)
    Sets attribute k if it exists, otherwise sets key k. A KeyError
    raised by set-item (only likely if you subclass Munch) will
    propagate as an AttributeError instead.

    >>> b = Munch(foo='bar', this_is='useful when subclassing')
    >>> hasattr(b.values, '__call__')
    True
    >>> b.values = 'uh oh'
    >>> b.values
    'uh oh'
    >>> b['values']
    Traceback (most recent call last):
        ...
    KeyError: 'values'

copy(self)
    D.copy() -> a shallow copy of D

----------------------------------------------------------------------
Class methods defined here:

fromDict(d, default_factory) from builtins.type
    Recursively transforms a dictionary into a Munch via copy.

    >>> b = Munch.fromDict({'urmom': {'sez': {'what': 'what'}}})
    >>> b.urmom.sez.what
    'what'

    See munchify for more info.

----------------------------------------------------------------------
Methods inherited from Munch:

__delattr__(self, k)
    Deletes attribute k if it exists, otherwise deletes key k. A KeyError
    raised by deleting the key--such as when the key is missing--will
    propagate as an AttributeError instead.

    >>> b = Munch(lol=42)
    >>> del b.lol
    >>> b.lol
    Traceback (most recent call last):
        ...
    AttributeError: lol

__dir__(self)
    Default dir() implementation.

__getattr__(self, k)
    Gets key if it exists, otherwise throws AttributeError.

    nb. __getattr__ is only called if key is not found in normal places.

    >>> b = Munch(bar='baz', lol={})
    >>> b.foo
    Traceback (most recent call last):
        ...
    AttributeError: foo

    >>> b.bar
    'baz'
    >>> getattr(b, 'bar')
    'baz'
    >>> b['bar']
    'baz'

    >>> b.lol is b['lol']
    True
    >>> b.lol is getattr(b, 'lol')
    True

__getstate__(self)
    Implement a serializable interface used for pickling.

    See https://docs.python.org/3.6/library/pickle.html.

__members__ = __dir__(self)

__setstate__(self, state)
    Implement a serializable interface used for pickling.

    See https://docs.python.org/3.6/library/pickle.html.

get(self, k, d=None)
    D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.

setdefault(self, k, d=None)
    D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

toDict(self)
    Recursively converts a munch back into a dictionary.

    >>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
    >>> sorted(b.toDict().items())
    [('foo', {'lol': True}), ('hello', 42), ('ponies', 'are pretty!')]

    See unmunchify for more info.

toJSON(self, **options)
    Serializes this Munch to JSON. Accepts the same keyword options as `json.dumps()`.

    >>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
    >>> json.dumps(b) == b.toJSON()
    True

toYAML(self, **options)
    Serializes this Munch to YAML, using `yaml.safe_dump()` if
    no `Dumper` is provided. See the PyYAML documentation for more info.

    >>> b = Munch(foo=['bar', Munch(lol=True)], hello=42)
    >>> import yaml
    >>> yaml.safe_dump(b, default_flow_style=True)
    '{foo: [bar, {lol: true}], hello: 42}\n'
    >>> b.toYAML(default_flow_style=True)
    '{foo: [bar, {lol: true}], hello: 42}\n'
    >>> yaml.dump(b, default_flow_style=True)
    '!munch.Munch {foo: [bar, !munch.Munch {lol: true}], hello: 42}\n'
    >>> b.toYAML(Dumper=yaml.Dumper, default_flow_style=True)
    '!munch.Munch {foo: [bar, !munch.Munch {lol: true}], hello: 42}\n'

update(self, *args, **kwargs)
    Override built-in method to call custom __setitem__ method that may
    be defined in subclasses.

----------------------------------------------------------------------
Class methods defined here:

fromDict(d, default=None) from builtins.type
    Recursively transforms a dictionary into a Munch via copy.

    >>> b = Munch.fromDict({'urmom': {'sez': {'what': 'what'}}})
    >>> b.urmom.sez.what
    'what'


A dictionary that provides attribute-style access.

>>> b = Munch()
>>> b.hello = 'world'
>>> b.hello
'world'
>>> b['hello'] += "!"
>>> b.hello
'world!'
>>> b.foo = Munch(lol=True)
>>> b.foo.lol
True
>>> b.foo is b['foo']
True

A Munch is a subclass of dict; it supports all the methods a dict does...

>>> sorted(b.keys())
['foo', 'hello']

Including update()...

>>> b.update({ 'ponies': 'are pretty!' }, hello=42)
>>> print (repr(b))
Munch({'ponies': 'are pretty!', 'foo': Munch({'lol': True}), 'hello': 42})

As well as iteration...

>>> sorted([ (k,b[k]) for k in b ])
[('foo', Munch({'lol': True})), ('hello', 42), ('ponies', 'are pretty!')]

And "splats".

>>> "The {knights} who say {ni}!".format(**Munch(knights='lolcats', ni='can haz'))
'The lolcats who say can haz!'

See unmunchify/Munch.toDict, munchify/Munch.fromDict for notes about conversion.


FUNCTIONS
    munchify(x, factory=<class 'munch.Munch'>)
        Recursively transforms a dictionary into a Munch via copy.

        >>> b = munchify({'urmom': {'sez': {'what': 'what'}}})
        >>> b.urmom.sez.what
        'what'

        munchify can handle intermediary dicts, lists and tuples (as well as
        their subclasses), but ymmv on custom datatypes.

        >>> b = munchify({ 'lol': ('cats', {'hah':'i win again'}),
        ...         'hello': [{'french':'salut', 'german':'hallo'}] })
        >>> b.hello[0].french
        'salut'
        >>> b.lol[1].hah
        'i win again'

        nb. As dicts are not hashable, they cannot be nested in sets/frozensets.

    unmunchify(x)
        Recursively converts a Munch into a dictionary.

        >>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
        >>> sorted(unmunchify(b).items())
        [('foo', {'lol': True}), ('hello', 42), ('ponies', 'are pretty!')]

        unmunchify will handle intermediary dicts, lists and tuples (as well as
        their subclasses), but ymmv on custom datatypes.

        >>> b = Munch(foo=['bar', Munch(lol=True)], hello=42,
        ...         ponies=('are pretty!', Munch(lies='are trouble!')))
        >>> sorted(unmunchify(b).items()) #doctest: +NORMALIZE_WHITESPACE
        [('foo', ['bar', {'lol': True}]), ('hello', 42), ('ponies', ('are pretty!', {'lies': 'are trouble!'}))]

        nb. As dicts are not hashable, they cannot be nested in sets/frozensets.
 

目录
相关文章
|
14天前
|
XML JSON 数据库
Python的标准库
Python的标准库
131 77
|
28天前
|
机器学习/深度学习 算法 数据挖掘
数据分析的 10 个最佳 Python 库
数据分析的 10 个最佳 Python 库
83 4
数据分析的 10 个最佳 Python 库
|
15天前
|
XML JSON 数据库
Python的标准库
Python的标准库
42 11
|
28天前
|
人工智能 API 开发工具
aisuite:吴恩达发布开源Python库,一个接口调用多个大模型
吴恩达发布的开源Python库aisuite,提供了一个统一的接口来调用多个大型语言模型(LLM)服务。支持包括OpenAI、Anthropic、Azure等在内的11个模型平台,简化了多模型管理和测试的工作,促进了人工智能技术的应用和发展。
107 1
aisuite:吴恩达发布开源Python库,一个接口调用多个大模型
|
15天前
|
数据可视化 Python
以下是一些常用的图表类型及其Python代码示例,使用Matplotlib和Seaborn库。
通过这些思维导图和分析说明表,您可以更直观地理解和选择适合的数据可视化图表类型,帮助更有效地展示和分析数据。
57 8
|
1月前
|
存储 人工智能 搜索推荐
Memoripy:支持 AI 应用上下文感知的记忆管理 Python 库
Memoripy 是一个 Python 库,用于管理 AI 应用中的上下文感知记忆,支持短期和长期存储,兼容 OpenAI 和 Ollama API。
95 6
Memoripy:支持 AI 应用上下文感知的记忆管理 Python 库
|
23天前
|
安全 API 文件存储
Yagmail邮件发送库:如何用Python实现自动化邮件营销?
本文详细介绍了如何使用Yagmail库实现自动化邮件营销。Yagmail是一个简洁强大的Python库,能简化邮件发送流程,支持文本、HTML邮件及附件发送,适用于数字营销场景。文章涵盖了Yagmail的基本使用、高级功能、案例分析及最佳实践,帮助读者轻松上手。
31 4
|
27天前
|
XML JSON API
如何使用Python将字典转换为XML
本文介绍了如何使用Python中的`xml.etree.ElementTree`库将字典数据结构转换为XML格式。通过定义递归函数处理字典到XML元素的转换,生成符合标准的XML文档,适用于与旧系统交互或需支持复杂文档结构的场景。示例代码展示了将一个简单字典转换为XML的具体实现过程。
17 1
|
1月前
|
Python
Python运算符优先级
Python运算符优先级。
22 3
|
1月前
|
Python
Python成员运算符
Python成员运算符
27 2