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.
 

目录
相关文章
|
5天前
|
SQL 关系型数据库 MySQL
MySQL操作利器——mysql-connector-python库详解
MySQL操作利器——mysql-connector-python库详解
26 0
|
3天前
|
存储 JSON 索引
一文让你彻底搞懂 Python 字典是怎么实现的
一文让你彻底搞懂 Python 字典是怎么实现的
26 13
|
3天前
|
数据挖掘 Python
【Python】应用:pyproj地理计算库应用
这篇博客介绍了 `pyproj` 地理计算库的应用,涵盖地理坐标系统转换与地图投影。通过示例代码展示了如何进行经纬度与UTM坐标的互转,并利用 `pyproj.Geod` 计算两点间的距离及方位角,助力地理数据分析。 安装 `pyproj`:`pip install pyproj`。更多内容欢迎关注本博客,一起学习进步! Pancake 🍰 不迷路。😉*★,°*:.☆( ̄▽ ̄)/$:*.°★* 😏
|
4天前
|
存储 数据安全/隐私保护 Python
Python常用数据结构——字典的应用
Python常用数据结构——字典的应用
|
4天前
|
数据挖掘 API 数据处理
Python 数据分析及预处理常用库
Python自身数据分析功能有限,需借助第三方库增强。常用库包括NumPy、pandas、Matplotlib等。NumPy由Numeric发展而来,提供了多维数组对象及各种API,支持高效的数据处理,如数学、逻辑运算等,常作为其他高级库如pandas和Matplotlib的依赖库。其内置函数处理速度极快,建议优先使用以提升程序效率。
7 0
|
4天前
|
存储 数据安全/隐私保护 Python
Python常用数据结构—字典
Python常用数据结构—字典
|
5天前
|
UED Python
Python requests库下载文件时展示进度条的实现方法
以上就是使用Python `requests`库下载文件时展示进度条的一种实现方法,它不仅简洁易懂,而且在实际应用中非常实用。
10 0
|
5天前
|
机器学习/深度学习 人工智能 数据可视化
# Python的一个非常cool的库Gradio
# Python的一个非常cool的库Gradio
16 0
|
5天前
|
监控 网络协议 数据库连接
Python3 监控端口:使用 socket 库
Python3 监控端口:使用 socket 库
15 0
|
5天前
|
数据挖掘 Python
​Python神奇之旅:探索NumPy库的力量
​Python神奇之旅:探索NumPy库的力量
11 0
下一篇
无影云桌面