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.
 

目录
相关文章
|
1天前
|
知识图谱 Python
Python入门:4.Python中的运算符
Python是一间强大而且便捷的编程语言,支持多种类型的运算符。在Python中,运算符被分为算术运算符、赋值运算符、复合赋值运算符、比较运算符和逻辑运算符等。本文将从基础到进阶进行分析,并通过一个综合案例展示其实际应用。
|
4天前
|
数据采集 JavaScript Android开发
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
29 7
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
|
28天前
|
测试技术 Python
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
106 31
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
|
1月前
|
机器学习/深度学习 存储 数据挖掘
Python图像处理实用指南:PIL库的多样化应用
本文介绍Python中PIL库在图像处理中的多样化应用,涵盖裁剪、调整大小、旋转、模糊、锐化、亮度和对比度调整、翻转、压缩及添加滤镜等操作。通过具体代码示例,展示如何轻松实现这些功能,帮助读者掌握高效图像处理技术,适用于图片美化、数据分析及机器学习等领域。
73 20
|
1月前
|
JSON 监控 安全
深入理解 Python 的 eval() 函数与空全局字典 {}
`eval()` 函数在 Python 中能将字符串解析为代码并执行,但伴随安全风险,尤其在处理不受信任的输入时。传递空全局字典 {} 可限制其访问内置对象,但仍存隐患。建议通过限制函数和变量、使用沙箱环境、避免复杂表达式、验证输入等提高安全性。更推荐使用 `ast.literal_eval()`、自定义解析器或 JSON 解析等替代方案,以确保代码安全性和可靠性。
45 2
|
2月前
|
XML JSON 数据库
Python的标准库
Python的标准库
185 77
|
2月前
|
XML JSON 数据库
Python的标准库
Python的标准库
71 11
|
2月前
|
数据可视化 Python
以下是一些常用的图表类型及其Python代码示例,使用Matplotlib和Seaborn库。
通过这些思维导图和分析说明表,您可以更直观地理解和选择适合的数据可视化图表类型,帮助更有效地展示和分析数据。
105 8
|
2月前
|
安全 API 文件存储
Yagmail邮件发送库:如何用Python实现自动化邮件营销?
本文详细介绍了如何使用Yagmail库实现自动化邮件营销。Yagmail是一个简洁强大的Python库,能简化邮件发送流程,支持文本、HTML邮件及附件发送,适用于数字营销场景。文章涵盖了Yagmail的基本使用、高级功能、案例分析及最佳实践,帮助读者轻松上手。
88 4
|
3月前
|
XML JSON API
如何使用Python将字典转换为XML
本文介绍了如何使用Python中的`xml.etree.ElementTree`库将字典数据结构转换为XML格式。通过定义递归函数处理字典到XML元素的转换,生成符合标准的XML文档,适用于与旧系统交互或需支持复杂文档结构的场景。示例代码展示了将一个简单字典转换为XML的具体实现过程。
31 1

热门文章

最新文章

推荐镜像

更多