-1

With xmltodict I managed to get my code from xml in a dict and now I want to create an excel. In this excel the header of a value is going to be all the parents (keys in the dict). For example:

dict = {"name":"Pete", "last-name": "Pencil", "adres":{"street": "example1street", "number":"5", "roommate":{"gender":"male"}}}

The value male will have the header: adres/roommate/gender.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • I think you were looking for it in a wrong way. Dict in a dict is equal to nested dict. So within stackoverflow you've got a post talking about it: [link](https://stackoverflow.com/questions/39233973/get-all-keys-of-a-nested-dictionary) – Tau n Ro Jun 20 '22 at 14:27
  • Could you write out what your expected output is? – BrokenBenchmark Jun 20 '22 at 17:34

1 Answers1

0

Here's a way to orgainze the data in the way your question asks:

d = {"name":"Pete", "last-name": "Pencil", "adres":{"street": "example1street", "number":"5", "roommate":{"gender":"male"}}}
print(d)
stack = [('', d)]
headerByValue = {}
while stack:
    name, top = stack.pop()
    if isinstance(top, dict):
        stack += (((name + '/' if name else '') + k, v) for k, v in top.items())
    else:
        headerByValue[name] = top

print(headerByValue)

Output:

{'adres/roommate/gender': 'male', 
'adres/number': '5', 
'adres/street': 'example1street', 
'last-name': 'Pencil', 
'name': 'Pete'}
constantstranger
  • 9,176
  • 2
  • 5
  • 19