Danny Xu
Danny Xu

Reputation: 101

How to split values in a nested dictionary by characters

Lets say I have a nested dictionary

nested_dict={"dict1":{"key1":"value1", "key2":"value2", "key3":"value3;value4"}}

Now I want to split value3 and value 4 under the same key like this,

nested_dict={"dict1":{"key1":"value1", "key2":"value2",  'key3': ['value3', 'value4']}}

What would be the best way to do so in Python?

Upvotes: 0

Views: 83

Answers (1)

Kuldeep Singh Sidhu
Kuldeep Singh Sidhu

Reputation: 3856

use the fact that dict is mutable and you can recursively change anything under the sun :P

nested_dict={"dict1":{"key1":"value1", "key2":"value2", "key3":"value3;value4"}}
def sol(d):
    for i in d:
        if type(d[i]) is dict:
            sol(d[i])
        else:
            d[i] = d[i].split(';')
            if len(d[i])==1: d[i] = d[i][0]
sol(nested_dict)
print(nested_dict)
{'dict1': {'key1': 'value1', 'key2': 'value2', 'key3': ['value3', 'value4']}}

Upvotes: 1

Related Questions