G
G
grecigor252021-07-17 00:51:24
Python
grecigor25, 2021-07-17 00:51:24

What is the name of the dictionary decomposition algorithm?

There is a dictionary

{
"a":"1", 
"b":{
      "c":{"d":"2",
             "e":"3",
            }
      "f":"4",
      }
"g":"5"
}


Need to turn it into this

{
"a":"1",
"b.c.d":"2",
"b.c.e":"3",
"b.f":"4",
"g":"5",
}


I understand that this is done recursively, checking instances, etc., but I can’t figure out how to solve this problem in my head, you can tell me the name of the algorithm for solving this problem, so that I can remember it or understand in which direction I need to move.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-07-17
@0xD34F

Not called at all. Traverse recursively nested elements, and that's it:

def nested_to_plain(obj):
  result = {}

  for key, val in obj.items():
    if type(val) == dict:
      result.update({ key + '.' + k: v for k, v in nested_to_plain(val).items() })
    else:
      result[key] = val

  return result

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question