How edit python dict in example?

Question:

I have a dict:

my_dict = {'some.key' : 'value'}

and i want to change it like this:

result = {'some' : {'key' : 'value'}}

how i can do this?
I need to this to create nested classes using dicts:

example:

my_dict = {'nested.key' : 'value'}

class Nested:
    key : str

class MyDict:
    nested : Nested

Answers:

I hope this function will help you

def foo(obj):
    result = {}

    for k, v in obj.items():
        keys = k.split('.')

        caret = result
        for i in range(len(keys)):
            curr_key = keys[i]

            if i == len(keys) - 1:
                caret[curr_key] = v
            else:
                caret.setdefault(curr_key, {})
                caret = caret[curr_key]

    return result

Not quite sure if I understand your question, but would

result = {key.split('.')[0]: {key.split('.')[1]: value} for key, value in my_dict.items()}

do the trick?

Answered By: Manuel

if you need this for real use, and not as a coding exercise, you can install extradict and use extradict.NestedData:


In [1]: from extradict import NestedData

In [2]: a = NestedData({'some.key' : 'value'})

In [3]: a["some"]
Out[3]: {'key': <str>}

In [4]: a["some"]["key"]
Out[4]: 'value'

In [5]: a.data
Out[5]: {'some': {'key': 'value'}}

(disclaimer: I am the package author)

Answered By: jsbueno

with recurtion it could look like this (having all keys unique is essential):

my_dict = {'key0' : 'value0',
           'nested.key' : 'value',
           'nested1.nested1.key1' : 'value1',
           'nested2.nested2.nested2.key2' : 'value2'}

def func(k,v):
    if not '.' in k: return {k:v}
    k1,k = k.split('.',1)
    return {k1:func(k,v)}

res = {}
for k,v in my_dict.items():
    res.update(func(k,v))

>>> res
'''
{'key0': 'value0',
 'nested': {'key': 'value'},
 'nested1': {'nested1': {'key1': 'value1'}},
 'nested2': {'nested2': {'nested2': {'key2': 'value2'}}}}
Answered By: SergFSM
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.