Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kkirsche/b835882134af0257c57b433d9a104ec0 to your computer and use it in GitHub Desktop.
Save kkirsche/b835882134af0257c57b433d9a104ec0 to your computer and use it in GitHub Desktop.
Convert a dictionary to an object (recursive).
class DictionaryUtility:
"""
Utility methods for dealing with dictionaries.
"""
@staticmethod
def to_object(item):
"""
Convert a dictionary to an object (recursive).
"""
def convert(item):
if isinstance(item, dict):
return type('jo', (), {k: convert(v) for k, v in item.iteritems()})
if isinstance(item, list):
def yield_convert(item):
for index, value in enumerate(item):
yield convert(value)
return list(yield_convert(item))
else:
return item
return convert(item)
@Elijas
Copy link

Elijas commented May 12, 2021

Another alternative:
pip install munch

Then:

from munch import Munch

a = Munch.fromDict({'b': {'c': 1}})
print(a.b.c) # Output: 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment