'Convert a dictionary with dot and array symbols in keys to proper dictionary format
I am new to python and I need to write a generic code that do the following for me:
Input Dictionary :
input_dict = {
"key1.key2.key3": 1,
"key4.key5": True,
"key6": 2,
"key7[arr_key1]": 5,
"key7[arr_key2.arr_subkey1]": "hello",
}
Desired output :
{
"key1": {
"key2": {
"key3": 1
}
},
"key4": {
"key5": True
},
"key6": 2,
"key7": [
{
"arr_key1": 5,
"arr_key2": {
"arr_subkey1": "hello"
}
}
]
}
Basically, it should create a nested dictionary if dot notation is found in key and if '[' is found then convert it to array first the continue with conversion of dot notation.
I have written this piece of code that works fine for dot notation but I am not figure out how to update it for array objects.
res = {}
for key, value in input_dict.items():
if "." in key:
temp = str(key).split(".")
last = temp[len(temp) - 1]
current_level = res
for part in temp:
if part != last:
if part not in res:
current_level[part] = {}
else:
current_level[part] = value
current_level = current_level[part]
else:
res[key] = value
print(res)
Any help is highly appreciated. Thanks in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
