2

My question is relatively simple: How do I recursively set object attributes matching the key-value pairs of a dictionary?

For example, given this dict:

my_dict = {
    "number": 0,
    "thing": True,
    "foo": {
        "bar": {
            "thing": "string"
        }
    }
}

I want to make an object with its keys as attributes, recursively:

>>> my_obj = some_method(my_dict)
>>> my_obj.number
0
>>> my_obj.foo.bar
{"thing": "string"}
>>> my_obj.foo.bar.thing
"string" 
frissyn
  • 77
  • 5

2 Answers2

3

https://github.com/Infinidat/munch

This library is meant to provide attribute style access to dictionaries.

For example:

>>> from bunch import bunchify
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
>>> x = bunchify(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
'bar'
Tarek Ahmed
  • 148
  • 9
2

Another way using builtin libs:

import json
from types import SimpleNamespace

my_dict = {
    "number": 0,
    "thing": True,
    "foo": {
        "bar": {
            "thing": "string"
        }
    }
}

dumped_data = json.dumps(my_dict)
result = json.loads(dumped_data, object_hook=lambda x: SimpleNamespace(**x))

result.number

>> 0

result.foo.bar.thing

>> string
Willian Vieira
  • 473
  • 2
  • 8