0
"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!

JULS
  • 11
  • 4
  • Oops, wrong link, I meant https://stackoverflow.com/questions/6027558/flatten-nested-dictionaries-compressing-keys/6027615#6027615 – Nick Jun 09 '20 at 03:16

2 Answers2

0

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'}
leopardxpreload
  • 767
  • 5
  • 17
0

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'}
Sundeep Pidugu
  • 2,377
  • 2
  • 21
  • 43