from types import SimpleNamespace

sn = SimpleNamespace(a=1, b=2, c=3)

vars(sn)
# returns {'a': 1, 'b': 2, 'c': 3}

sn.__dict__
# also returns {'a': 1, 'b': 2, 'c': 3}
Answer from Николай Гордеев on Stack Overflow
🌐
DEV Community
dev.to › taqkarim › extending-simplenamespace-for-nested-dictionaries-58e8
Extending SimpleNamespace for Nested Dictionaries - DEV Community
April 13, 2020 - from types import SimpleNamespace # this is how SimpleNamespace looks when output SimpleNamespace(**my_dict) # namespace(a={'d': 4}, b=2, c=3, e=[5, 6, 7, {'f': 8}]) class RecursiveNamespace(SimpleNamespace): @staticmethod def map_entry(entry): if isinstance(entry, dict): return RecursiveNamespace(**entry) return entry def __init__(self, **kwargs): super().__init__(**kwargs) for key, val in kwargs.items(): if type(val) == dict: setattr(self, key, RecursiveNamespace(**val)) elif type(val) == list: setattr(self, key, list(map(self.map_entry, val))) # this is how RecursiveNamespace looks when output RecursiveNamespace(**my_dict) # RecursiveNamespace( # a=RecursiveNamespace(d=4), # b=2, # c=3, # e=[5, 6, 7, RecursiveNamespace(f=8)])
Discussions

python - How to initialize a SimpleNamespace from a dict - Stack Overflow
I'm sure this must be simple, but I could not find the answer. I have a dictionary like: d = {'a': 1, 'b':2} I'd like to access that via dot notation, like: d.a The SimpleNamespace is designed for More on stackoverflow.com
🌐 stackoverflow.com
python - How to use a list of attributes of SimpleNamespace instead of list of dict keys? - Stack Overflow
How do I implement the get_average function for this SimpleNamespace syntax without revealing the underlying dict structure? Also note, I am not a professional in Python so if you smell wrong code, please suggest a better way (data structure / type) to solve this problem (OOP-like dicts). More on stackoverflow.com
🌐 stackoverflow.com
How to convert a nested python dictionary into a simple namespace? - Stack Overflow
Note that I had to modify the parse function slightly, so that it handles nested dicts within a list object, for example. from timeit import timeit from types import SimpleNamespace from attrdict import AttrDict from dotwiz import DotWiz example_input = {'key0a': "test", 'key0b': {'key1a': ... More on stackoverflow.com
🌐 stackoverflow.com
Typing rules for SimpleNamespace - Typing - Discussions on Python.org
What would be needed to be able ... now, it's Any I’d love to use SimpleNamespace as an inline single frozen instance, but the editors don’t know the attributes of my_obj. If I never reuse the class, it’s extremely verbose. If I use dict then the keys and types are not ... More on discuss.python.org
🌐 discuss.python.org
1
August 15, 2024
🌐
LWN.net
lwn.net › Articles › 818777
Improving Python's SimpleNamespace [LWN.net]
Python's SimpleNamespace class provides an easy way for a programmer to create an object to store values as attributes without creating their own (almost empty) class. While it is useful (and used) in its present form, Raymond Hettinger thinks it could be better. He would like to see the hooks used by mappings (e.g. dictionaries...
🌐
Medium
medium.com › @shashank_iyer › simplify-json-access-with-simplenamespace-e91f5a09345b
Simplify JSON access with SimpleNamespace | by Shashank Iyer | Medium
December 21, 2021 - This table shows the type conversions from the JSON world to the Python world. We know that the 2 load methods convert a JSON “object” to a Python “dict”.
🌐
Narkive
python-ideas.python.narkive.com › sRFw09BM › a-simple-namespace-type
a simple namespace type
But the "feel" of the type is different, and inherits more of the underlying type (namedtuple is immutable and has a fixed set of keys, whereas the type proposed here is mutable and allows arbitrary keys as long as they look like Python names). Post by Eric Snow Regardless, if you want to do dict things then you can get the underlying dict using vars(ns) or ns.__dict__ on your instance. Alternately you can subclass the SimpleNamespace type to get all the extra goodies you want, as I showed with the Namespace class at the bottom of my first message.
🌐
Jugmac00
jugmac00.github.io › today i learned › how to group data easily with simplenamespace
How to Group Data Easily With SimpleNamespace | Jürgen Gmach
November 13, 2020 - class SimpleNamespace: def __init__(self, /, **kwargs): self.__dict__.update(kwargs) def __repr__(self): items = (f"{k}={v!r}" for k, v in self.__dict__.items()) return "{}({})".format(type(self).__name__, ", ".join(items)) def __eq__(self, other): return self.__dict__ == other.__dict__
🌐
Stack Overflow
stackoverflow.com › questions › 64160345 › how-to-use-a-list-of-attributes-of-simplenamespace-instead-of-list-of-dict-keys
python - How to use a list of attributes of SimpleNamespace instead of list of dict keys? - Stack Overflow
If you need it to do other things, and want to use more "OOP-like" syntax, then write a class definition. ... SimpleNamespace is just a wrapper for the dict so you can just pass the dict property.
Find elsewhere
Top answer
1 of 6
5

2022 answer: now there is a tiny, relatively fast library I have published, called dotwiz, which alternatively can be used to provide easy dot access for a python dict object.

It should, coincidentally, be a little faster than the other options -- I've added a quick and dirty benchmark code I put together using the timeit module below, timing against both a attrdict and SimpleNamespace approach -- the latter of which actually performs pretty solid in times.

Note that I had to modify the parse function slightly, so that it handles nested dicts within a list object, for example.

from timeit import timeit
from types import SimpleNamespace

from attrdict import AttrDict
from dotwiz import DotWiz


example_input = {'key0a': "test", 'key0b': {'key1a': [{'key2a': 'end', 'key2b': "test"}], 'key1b': "test"},
                 "something": "else"}


def parse(d):
    x = SimpleNamespace()
    _ = [setattr(x, k,
                 parse(v) if isinstance(v, dict)
                 else [parse(e) for e in v] if isinstance(v, list)
                 else v) for k, v in d.items()]
    return x


print('-- Create')
print('attrdict:         ', round(timeit('AttrDict(example_input)', globals=globals()), 2))
print('dotwiz:           ', round(timeit('DotWiz(example_input)', globals=globals()), 2))
print('SimpleNamespace:  ', round(timeit('parse(example_input)', globals=globals()), 2))
print()

dw = DotWiz(example_input)
ns = parse(example_input)
ad = AttrDict(example_input)

print('-- Get')
print('attrdict:         ', round(timeit('ad.key0b.key1a[0].key2a', globals=globals()), 2))
print('dotwiz:           ', round(timeit('dw.key0b.key1a[0].key2a', globals=globals()), 2))
print('SimpleNamespace:  ', round(timeit('ns.key0b.key1a[0].key2a', globals=globals()), 2))
print()

print(ad)
print(dw)
print(ns)

assert ad.key0b.key1a[0].key2a \
       == dw.key0b.key1a[0].key2a \
       == ns.key0b.key1a[0].key2a \
       == 'end'

Here are the results, on my M1 Mac Pro laptop:

attrdict:          0.69
dotwiz:            1.3
SimpleNamespace:   1.38

-- Get
attrdict:          6.06
dotwiz:            0.06
SimpleNamespace:   0.06

The dotwiz library can be installed with pip:

$ pip install dotwiz
2 of 6
3

Based on mujjija's solution this is what I came up with. Full code below

from types import SimpleNamespace


def parse(data):
    if type(data) is list:
        return list(map(parse, data))
    elif type(data) is dict:
        sns = SimpleNamespace()
        for key, value in data.items():
            setattr(sns, key, parse(value))
        return sns
    else:
        return data


info = {
    'country': 'Australia',
    'number': 1,
    'slangs': [
        'no worries mate',
        'winner winner chicken dinner',
        {
            'no_slangs': [123, {'definately_not': 'hello'}]
        }
    ],
    'tradie': {
        'name': 'Rizza',
        'occupation': 'sparkie'
    }
}

d = parse(info)
assert d.country == 'Australia'
assert d.number == 1
assert d.slangs[0] == 'no worries mate'
assert d.slangs[1] == 'winner winner chicken dinner'
assert d.slangs[2].no_slangs[0] == 123
assert d.slangs[2].no_slangs[1].definately_not == 'hello'
assert d.tradie.name == 'Rizza'
assert d.tradie.occupation == 'sparkie'

If I'm not mistaken, Python doesn't support Tail Call Optimization. So please be careful when using deep recursive functions in Python. For small examples, it should be fine.

Update

Another version. object_hook does the magic of nesting. I prefer this version because I can directly feed them to the jinja2 template engine.

import json


class _DotDict(dict):
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__


def dot(data=None):
    if data is []:
        return []
    return json.loads(json.dumps(data), object_hook=_DotDict) if data else _DotDict()
🌐
Google Groups
groups.google.com › g › python-ideas › c › C-h-cHTAnU0
[Python-ideas] a simple namespace type
Regardless, if you want to do dict things then you can get the underlying dict using vars(ns) or ns.__dict__ on your instance. Alternately you can subclass the SimpleNamespace type to get all the extra goodies you want, as I showed with the Namespace class at the bottom of my first message.
🌐
Python.org
discuss.python.org › typing
Typing rules for SimpleNamespace - Typing - Discussions on Python.org
August 15, 2024 - What would be needed to be able ... now, it's Any I’d love to use SimpleNamespace as an inline single frozen instance, but the editors don’t know the attributes of my_obj. If I never reuse the class, it’s extremely verbose. If I use dict then the keys and types are not ...
🌐
ProgramCreek
programcreek.com › python › example › 82644 › types.SimpleNamespace
Python Examples of types.SimpleNamespace
You may also want to check out all available functions/classes of the module types , or try the search function . ... def _parse_optimizer(opt): """ Examples: 1. "optimize": "SGD" 2. "optimize": { "optimizer": "SGD", "learning_rate": 0.05 } """ kwargs = {} if isinstance(opt, str): return SimpleNamespace(optimizer=opt, kwargs=kwargs) elif isinstance(opt, dict): optimizer = opt.get("optimizer", kwargs) if not optimizer: raise ValueError(f"optimizer config: {opt} invalid") kwargs = {k: v for k, v in opt.items() if k != "optimizer"} return SimpleNamespace(optimizer=optimizer, kwargs=kwargs) else: raise ValueError(f"invalid type for optimize: {type(opt)}")
🌐
Reddit
reddit.com › r/learnpython › best way to get a dict-like object with dot notations? class attributes, or other options?
r/learnpython on Reddit: Best way to get a dict-like object with dot notations? Class attributes, or other options?
June 3, 2023 -

Edit: Solved, thank you BumbleSpork, and everyone else for your help. What I was looking for is types.SimpleNamespace.


Hey!

I would like to create something like a dict, with a bunch of keys, but access them as Foo.bar rather than foo["bar"]

I know I can use a class with attributes for this:

class Foo:
    bar = "this works"

print(Foo.bar) # prints "this works"

Is this the best way? Are there classes for this specific use case in the standard library? Thanks!

🌐
Python
mail.python.org › archives › list › python-dev@python.org › thread › JOMND56PJGRN7FQQLLCWONE5Z7R2EKXW
Mailman 3 Improvement to SimpleNamespace - Python-Dev - python.org
The core idea is keep the simple attribute access but make it easier to load data programmatically: >>> ns = SimpleNamespace(roses='red', violets='blue') >>> thing = input() sugar >>> quality = input() sweet >>> setattr(ns, thing, quality) # current >>> ns['sugar'] = 'sweet' # proposed If the PEP 584 __ior__ method were supported, updating a SimpleNamespace would be much cleaner: ns |= some_dict I posted an issue on the tracker: https://bugs.python.org/issue40284 .
🌐
GitHub
github.com › python › cpython › issues › 108191
Allow specifying SimpleNamespace attributes as a mapping/iterable in a positional argument · Issue #108191 · python/cpython
August 21, 2023 - The reason for adding AttrDict was to allow JSON object attributes to be accessed as Python object attributes rather than dict keys. The reason for not using SimpleNamespace for this was that you need to use a wrapper lambda x: SimpleNamespace(**x), which makes this solution less obvious.
Author   serhiy-storchaka
Top answer
1 of 3
46

SimpleNamespace is basically just a nice facade on top of a dictionary. It allows you to use properties instead of index keys. This is nice as it is super flexible and easy to manipulate.

The downside of that flexibility is that it doesn't provide any structure. There is nothing to stop someone from calling SimpleNamespace(x=ax, y=ay) (and del a.z at some point later). If this instance gets passed to your function, the exception occurs when you try to access the field.

In contrast, namedtuple lets you create a structured type. The type will have a name and it will know what fields it is supposed to have. You won't be able to make an instance without each of those field and they can't be removed later. Additionally, the instance is immutable, so you will know that the value in a.x will always be the same.

It's up to you to decide if you need the flexibility that SimpleNamespace gives you, or if you prefer to have the structure and guarantees provided by namedtuple.

2 of 3
4

I really like the answer about structured versus not, so I'm just providing a concrete example below.

SimpleNamespace will accept keys that begin with _. If you're looking for a quick and easy way to turn, say, JSON you don't control into objects with field names, this is very handy:

d = {"_id": 2342122, "text": "hi there!"} # Elasticsearch gives this id!
e = SimpleNamespace(**d) # works
Name = namedtuple("Name", sorted(d)) # ValueError so we can't do Name(**d)

Note above that you can see that namedtuple gives us a whole extra object that SimpleNamespace never will. Each SimpleNamespace is really a "unique snowflake", whereas namedtuple exists without ever being instantiated with any concrete values. Wherever you have need of abstractions that generalize on concrete values, you probably should prefer it.

🌐
YouTube
youtube.com › watch
Csv Parsing - From List to Dict to (SimpleNamespace) Object
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
GitHub
github.com › theskumar › python-dotenv › issues › 325
Option to return dotenv dict as a SimpleNamespace · Issue #325 · theskumar/python-dotenv
May 17, 2021 - Would you accept something like this? So I could have dot accessible variables very simply. from types import SimpleNamespace def dotenv_namespace(*args, **kwargs): return SimpleNamespace(**dotenv_values(*args, **kwargs))
Published   May 17, 2021
Author   adammarples
🌐
Reddit
reddit.com › r/python › silly question: what's the difference between dict and namespace? is it okay to use them interchangeably?
r/Python on Reddit: Silly question: What's the difference between dict and Namespace? Is it okay to use them interchangeably?
April 20, 2015 - A list of tuple pairs is a mapping that isn't a dict, for instance.) ... A namespace is essentially a collection of names bound to values. They are sometimes implemented by a dict "under the hood", but not always, and the implementation detail is really irrelevant, and they're not the same thing.
🌐
You.com
you.com › search
convert simplenamespace to dict 🔎 Your Personalized AI Assistant.
Conversational and continuously learning, You.com enhances web search, writing, coding, digital art creation, and solving complex problems.