0

I want to convert

dct = {"a":1,"b":{"c":2,"d":{"z":5,"t":12}}} 

to

lst = ["a:1","b:c:2","b:d:z:5","b:d:t:12"] 

in Python?

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Ayufi
  • 1
  • 4

1 Answers1

2

Recursively:

def flatten(dct, path="",lst=None):
    if not lst: lst = []
    for key,value in dct.items():
        if type(value) is dict:
            flatten(value, f"{path}{key}:", lst)
        else:
            lst.append(f"{path}{key}:{value}")
    return lst

print(flatten({"a":1,"b":{"c":2,"d":{"z":5,"t":12}}}))

Outputs:

['a:1', 'b:c:2', 'b:d:z:5', 'b:d:t:12']

Another version, as suggested in the comments.
Credit to: @Ch3steR

def flatten(dct, path=""):
    lst = []
    for key,value in dct.items():
        if isinstance(value, dict):
            lst.extend(flatten(value, f"{path}{key}:"))
        else:
            lst.append(f"{path}{key}:{value}")
    return lst
 
print(flatten({"a":1,"b":{"c":2,"d":{"z":5,"t":12}}}))
001
  • 13,291
  • 5
  • 35
  • 66
  • 2
    The solution would be a victim of ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/q/1132941/12416453) – Ch3steR Nov 04 '21 at 17:56
  • @Ch3steR Yeah. Updated. – 001 Nov 04 '21 at 18:02
  • 1
    can't you just remove it from the parameters, and have it inside? `lst = []` – Mahrkeenerh Nov 04 '21 at 18:03
  • @Mahrkeenerh No. That would create a new list each time the function is recursively called and I only want one list. Well, you probably could and return it and combine with previous list, but I think this is easier. – 001 Nov 04 '21 at 18:04
  • @JohnnyMopp You can try something like this: https://ideone.com/hp5dHB – Ch3steR Nov 04 '21 at 18:05
  • 1
    One more suggestion would be using `isinstance`. Related: https://stackoverflow.com/q/1549801/12416453 – Ch3steR Nov 04 '21 at 18:08
  • @Ch3steR Thanks for the input. As a primarily C++ programmer who occasionally works in Python, it is always welcome. – 001 Nov 04 '21 at 18:11
  • 1
    @JohnnyMopp I'm really glad you took it in a positive way. I learnt Python through SO never took a course. It was only possible due to many helpful individuals who suggested best practices in python in the comments. I'm doing the same helping the community in my capacity. :) – Ch3steR Nov 04 '21 at 18:23