Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for The Flat Dictionary by Bozenka
def flatten(dictionary: dict[str, str | dict]) -> dict[str, str]:
while dict in [type(x) for x in dictionary.values()]:
ref = dictionary.copy()
for key,value in ref.items():
if type(value) is dict:
if len(value.keys()):
for k in value.keys():
dictionary[f"{key}/{k}"] = dictionary[key].pop(k)
if not len(value.keys()):
dictionary.pop(key)
break
else:
dictionary[key]=""
return dictionary
print("Example:")
print(flatten({"key": "value"}))
# These "asserts" are used for self-checking
assert flatten({"key": "value"}) == {"key": "value"}
assert flatten({"key": {"deeper": {"more": {"enough": "value"}}}}) == {
"key/deeper/more/enough": "value"
}
assert flatten({"empty": {}}) == {"empty": ""}
assert flatten(
{
"name": {"first": "One", "last": "Drone"},
"job": "scout",
"recent": {},
"additional": {"place": {"zone": "1", "cell": "2"}},
}
) == {
"name/first": "One",
"name/last": "Drone",
"job": "scout",
"recent": "",
"additional/place/zone": "1",
"additional/place/cell": "2",
}
print("The mission is done! Click 'Check Solution' to earn rewards!")
Feb. 5, 2024
Comments: