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.
 

目录
相关文章
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
751 2
|
存储 人工智能 测试技术
如何使用LangChain的Python库结合DeepSeek进行多轮次对话?
本文介绍如何使用LangChain结合DeepSeek实现多轮对话,测开人员可借此自动生成测试用例,提升自动化测试效率。
2474 125
如何使用LangChain的Python库结合DeepSeek进行多轮次对话?
|
监控 数据可视化 数据挖掘
Python Rich库使用指南:打造更美观的命令行应用
Rich库是Python的终端美化利器,支持彩色文本、智能表格、动态进度条和语法高亮,大幅提升命令行应用的可视化效果与用户体验。
1253 0
|
传感器 运维 前端开发
Python离群值检测实战:使用distfit库实现基于分布拟合的异常检测
本文解析异常(anomaly)与新颖性(novelty)检测的本质差异,结合distfit库演示基于概率密度拟合的单变量无监督异常检测方法,涵盖全局、上下文与集体离群值识别,助力构建高可解释性模型。
866 10
Python离群值检测实战:使用distfit库实现基于分布拟合的异常检测
|
数据可视化 关系型数据库 MySQL
【可视化大屏】全流程讲解用python的pyecharts库实现拖拽可视化大屏的背后原理,简单粗暴!
本文详解基于Python的电影TOP250数据可视化大屏开发全流程,涵盖爬虫、数据存储、分析及可视化。使用requests+BeautifulSoup爬取数据,pandas存入MySQL,pyecharts实现柱状图、饼图、词云图、散点图等多种图表,并通过Page组件拖拽布局组合成大屏,支持多种主题切换,附完整源码与视频讲解。
1206 4
【可视化大屏】全流程讲解用python的pyecharts库实现拖拽可视化大屏的背后原理,简单粗暴!
|
Python
Python编程:运算符详解
本文全面详解Python各类运算符,涵盖算术、比较、逻辑、赋值、位、身份、成员运算符及优先级规则,结合实例代码与运行结果,助你深入掌握Python运算符的使用方法与应用场景。
730 3
|
运维 Linux 开发者
Linux系统中使用Python的ping3库进行网络连通性测试
以上步骤展示了如何利用 Python 的 `ping3` 库来检测网络连通性,并且提供了基本错误处理方法以确保程序能够优雅地处理各种意外情形。通过简洁明快、易读易懂、实操性强等特点使得该方法非常适合开发者或系统管理员快速集成至自动化工具链之内进行日常运维任务之需求满足。
897 18
|
机器学习/深度学习 API 异构计算
JAX快速上手:从NumPy到GPU加速的Python高性能计算库入门教程
JAX是Google开发的高性能数值计算库,旨在解决NumPy在现代计算需求下的局限性。它不仅兼容NumPy的API,还引入了自动微分、GPU/TPU加速和即时编译(JIT)等关键功能,显著提升了计算效率。JAX适用于机器学习、科学模拟等需要大规模计算和梯度优化的场景,为Python在高性能计算领域开辟了新路径。
1250 0
JAX快速上手:从NumPy到GPU加速的Python高性能计算库入门教程
|
存储 JSON 数据管理
Python字典:高效数据管理的瑞士军刀
Python字典基于哈希表实现,提供接近O(1)的高效查找,支持增删改查、遍历、合并等丰富操作,广泛应用于计数、缓存、配置管理及JSON处理。其灵活性与性能使其成为数据处理的核心工具。
978 0
|
存储 缓存 安全
Python字典:从入门到精通的实用指南
Python字典如瑞士军刀般强大,以键值对实现高效数据存储与查找,广泛应用于配置管理、缓存、统计等场景。本文详解字典基础、进阶技巧、实战应用与常见陷阱,助你掌握这一核心数据结构,写出更高效、优雅的Python代码。
506 0

推荐镜像

更多