Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recursive dict merge #65

Closed
zepengchen opened this issue Aug 25, 2020 · 2 comments
Closed

Recursive dict merge #65

zepengchen opened this issue Aug 25, 2020 · 2 comments

Comments

@zepengchen
Copy link

Thanks for creating this useful package.

Could you add a merge(self, other_munch_obj/mapping_obj) function to merge them recursively.

Thanks in advance.
Jason.

@d1618033
Copy link

Hey Jason,

Happy to hear you're enjoying this package.

The goal of munch is to be a simple alternative to python's standard dict that supports attribute-style access, without too many additional features besides that.

The merge function idea you suggested sounds really cool, but unfortunately it would be a bit of a feature creep to add it to Munch.

You can always extend the Munch class using inheritance or composition and add this functionality in your own repository if you'd like.

Best of luck,
David

@gleon99 gleon99 closed this as completed Aug 26, 2020
@zepengchen
Copy link
Author

Thank you, David,

I use below code to merge 2 dict recursively, then create a new munch object from the new dict object.
def dict_merge(dct, merge_dct):
# https://gist.github.com/angstwad/bf22d1822c38a92ec0a9
""" Recursive dict merge. Inspired by :meth:dict.update(), instead of
updating only top-level keys, dict_merge recurses down into dicts nested
to an arbitrary depth, updating keys. The merge_dct is merged into
dct.
:param dct: dict onto which the merge is executed
:param merge_dct: dct merged into dct
:return: None
"""
for k, v in merge_dct.items():
if (k in dct and isinstance(dct[k], munch.Mapping) and isinstance(merge_dct[k], munch.Mapping)):
dict_merge(dct[k], merge_dct[k])
else:
dct[k] = merge_dct[k]

The code doesn't process list(tuple), but it is enough for me now.

Regards,
Jason.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants