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

server/2024/9/22 15:20:53/

munch

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

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

安装

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

pip install munch

使用

1. 创建空对象
python">from munch import Munch# 创建一个空的Munch对象
data = Munch()# 添加键值对
data.name = 'Hann'
data.age = 50
2. 创建于字典
python">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()

python">from munch import Munchdata = 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.


http://www.ppmy.cn/server/8072.html

相关文章

【Hadoop】- YARN架构[7]

前言 Yarn架构是一个用于管理和调度Hadoop集群资源的系统。它是Hadoop生态系统的一部分&#xff0c;主要用于解决Hadoop中的资源管理问题。 通过使用Yarn架构&#xff0c;Hadoop集群中的不同应用程序可以共享集群资源&#xff0c;并根据需要动态分配和回收资源。这种灵活的资…

CX5120-0125倍福CPU模块维修PLC控制器CX5120全系列主机电脑深圳捷达工控维修

工业计算机服务与维修 为任何品牌的工业计算机、显示器、人机界面 (HMI) 和面板计算设备提供服务、维修和改造。您可以信赖我们延长生命周期&#xff0c;包括不再投放市场的产品。 工业计算机维修与保养 您的工业计算机专家 工业计算机维修服务 深圳捷达工控维修深知做好工业…

【MySQL】脏读,幻读,不可重复读

脏读、幻读、不可重复读 一、脏读 二、幻读 三、不可重复读 四、脏读、幻读、不可重复读的区别 一、脏读 脏读主要发生在隔离级别很低的事务之间&#xff0c;就比如隔离级别设为Read Uncommitted,也就是读为提交。当我们有多个数据库并发的访问一张表的时候&#xff0c;就…

前后端交互概念

前后端交互概念 1前后端分离开发概念2搭建后端环境2.1配置文件commomcommon-utilservice-utilmodelservice gitee使用 1前后端分离开发概念 前段&#xff1a;运用html、css、js和现成库&#xff0c;对数据作展示。 后端&#xff1a;运用Java和Java框架&#xff0c;提供数据或操…

【java毕业设计】 基于Spring Boot+mysql的课程作业管理系设计与实现(程序源码)-课程作业管理系

基于Spring Bootmysql的课程作业管理系设计与实现&#xff08;程序源码毕业论文&#xff09; 大家好&#xff0c;今天给大家介绍基于Spring Bootmysql的课程作业管理系设计与实现&#xff0c;本论文只截取部分文章重点&#xff0c;文章末尾附有本毕业设计完整源码及论文的获取方…

Basic TCP Server Client

Server #include <stdio.h> #include <string.h> #include <unistd.h> // read and write (TCP); sendto and recvfrom (UDP) #include <arpa/inet.h> // 包含#include <sys/socket.h>int main(int argc, char* argv[]) {// 1. 创建监听fdint f…

AI安全之问:我们的智能助手真的安全吗?

在我们日益依赖人工智能来撰写文档、编写程序代码、甚至创作艺术作品的今天&#xff0c;我们是否曾经想过这些智能系统可能面临的被恶意操纵的风险&#xff1f; 分享几个网站 GPT-3.5研究测试&#xff1a; https://hujiaoai.cn GPT-4研究测试&#xff1a; https://higpt4.cn…

C++相关概念和易错语法(8)(匿名对象、构造+拷贝构造优化、构造析构顺序)

1.匿名对象 当我们实例化对象后&#xff0c;有的对象可能只使用一次&#xff0c;之后就没用了。这个时候我们往往要主动去析构它&#xff0c;否则会占着浪费空间。但是如果遇到大量的这种情况&#xff0c;我们并不想每次都去创建对象、调用、析构&#xff0c;这样会写出很多重…