0

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"}
noamt
  • 7,397
  • 2
  • 37
  • 59
  • 6
    That's not a valid literal - did you mean `{"a": "b", "c": "d", "something": {"e": "E"}}`? Also, what code have you tried so far? – rassar Oct 25 '19 at 10:58

2 Answers2

3

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'}
j-i-l
  • 10,281
  • 3
  • 53
  • 70
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
  • I got this problem from a technical job interview (on skype) and was unable to solve this problem. She told me to convert into one dictionary. You are right , this is not a valid dict. Thanks dear for help. – sudeep basak Oct 25 '19 at 11:41
0

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'}

Koen G.
  • 738
  • 5
  • 10
  • I got this problem from a technical job interview (on skype) and was unable to solve this problem. She told me to convert into one dictionary. You are right , this is not a valid dict. Thanks dear for help. – sudeep basak Oct 25 '19 at 11:41