I have a dictionary like this:
a = {"a": "b", "c": "d", {"e": "E", "f": "F"}}
and I want to convert it to:
b = {"a": "b", "c": "d", "e": "E", "f": "F"}
I have a dictionary like this:
a = {"a": "b", "c": "d", {"e": "E", "f": "F"}}
and I want to convert it to:
b = {"a": "b", "c": "d", "e": "E", "f": "F"}
First your dict is not valid, it should be always a key value pair. Below it is what should be case for your dict
a = {"a": "b", "c": "d", 'something':{"e": "E", "f": "F"}}
def func(dic):
re ={}
for k,v in dic.items():
if isinstance(v, dict):
re.update(v)
else:
re.update({k:v})
return re
print(func(a))
output
{'a': 'b', 'c': 'd', 'e': 'E', 'f': 'F'}
If you're fine with losing the key to which your inner dict belongs to (you did not specify what to do with it), I would do it recursively:
def unnest_dict(d):
result = {}
for k,v in d.items():
if isinstance(v, dict):
result.update(unnest_dict(v))
else:
result[k] = v
return result
unnest_dict({"a": "b", "c": "d", "something":{"e": "E", "f": "F"}})
{'a': 'b', 'c': 'd', 'e': 'E', 'f': 'F'}