Home > Software design >  How edit python dict in example?
How edit python dict in example?

Time:08-20

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

CodePudding user response:

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)

CodePudding user response:

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?

CodePudding user response:

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

CodePudding user response:

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'}}}}
  • Related