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?
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?
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}}}))