Skip to content

Nester dict to simplenamespace #13

@EED85

Description

@EED85

from types import SimpleNamespace

def dict_to_namespace(d):
if isinstance(d, dict):
return SimpleNamespace(**{k: dict_to_namespace(v) for k, v in d.items()})
elif isinstance(d, list):
return [dict_to_namespace(item) for item in d]
else:
return d

nested_dict = {
"user": {
"name": "Alice",
"address": {
"city": "Wonderland",
"zip": "12345"
},
"hobbies": ["reading", {"type": "adventure"}]
}
}

ns = dict_to_namespace(nested_dict)
print(ns.user.name) # Alice
print(ns.user.address.city) # Wonderland
print(ns.user.hobbies[1].type) # adventure

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions