"a": "a",
"b": "b",
"c and d": {
"c": "c",
"d": "d"
}
How do I convert this to below dictionary in python3?
"a": "a",
"b": "b",
"c": "c",
"d": "d"
Thanks in advance!
"a": "a",
"b": "b",
"c and d": {
"c": "c",
"d": "d"
}
How do I convert this to below dictionary in python3?
"a": "a",
"b": "b",
"c": "c",
"d": "d"
Thanks in advance!
Try this:
# New squeaky clean dict
new = {}
for k, v in old.items(): # Cycle through each key (k) and value (v)
if 'and' in k: # If there is the word 'and' - append the first (0) and last (-1) of the dict
new[k[0]] = old[k][k[0]]
new[k[-1]] = old[k][k[-1]]
else: # Otherwise just add the old value
new[k] = v
print(old)
print(new)
Output:
{'a': 'a', 'b': 'b', 'c and d': {'c': 'c', 'd': 'd'}}
{'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}
This could be the easiest workaround.
a = {
"a": "a",
"b": "b",
"c and d": {
"c": "c",
"d": "d"
}
}
s = {}
def Merge(dict1, dict2):
return(dict2.update(dict1))
for key, value in a.items():
if(type(value) is dict):
Merge(value, s)
else:
Merge({key:value}, s)
print(s)
Result :
{'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}