-2

I have a complex dict, something like this:

d = {
  "key1": "value1",
  "key2": {
    "key3": "value3",
    "key4": {
      "key5": "value5",
      "key6": [{"keys1": "value_keys1"}]
    }
}

And I want to turn it on a simple key value

{
  "key1": "value1",
  "key2_key3": "value3",
  "key2_key4_key5": "value5",
  "key2_key4_key6_0_keys1": "value_keys1",

}

How can I do this on python?

I tried this:

def flat_dict_helper(prepend, d):
    if len(prepend) > 0:
        prepend = prepend + "_"
    for k in d:
        i = d[k]
        if isinstance(i, dict):
            r = flat_dict_helper(prepend + k, i)
            for j in r:
                yield j
        else:
            yield (prepend + k, i)


def flat_dict(d):
    return dict(flat_dict_helper("", d))

But this wont work on some cases, when there is a list inside for example

Rodrigo
  • 135
  • 4
  • 45
  • 107
  • 1
    Just add a branch for dealing with `isinstance(i, list)` – ddejohn Nov 03 '21 at 16:16
  • 1
    You mention `this wont work on some cases` but the only other case you mention is with `list`. If you have other cases, you need to specify all of them. – Random Davis Nov 03 '21 at 16:59

1 Answers1

3

You have to specify the behavior in the case of list:

def flat_dict_helper(prepend, d):
    prepend += "_" if len(prepend) else prepend
    for k in d:
        i = d[k]
        if isinstance(i, dict):
            r = flat_dict_helper(prepend + k, i)
            for j in r:
                yield j
        elif isinstance(i, list):
            for idx, element in enumerate(i):
                r = flat_dict_helper('{}{}_{}'.format(prepend, k, idx), element)
                for j in r:
                    yield j
        else:
            yield (prepend + k, i)



def flat_dict(d):
    return dict(flat_dict_helper("", d))

>>> flat_dict(d)
{'key1': 'value1', 'key2_key3': 'value3', 'key2_key4_key5': 'value5', 'key2_key4_key6_0_keys1': 'value_keys1'}


Andrea Barnabò
  • 534
  • 6
  • 19