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 _D_
def flatten(src):
def _flatten(src, target=None, prefix=''):
if target is None:
target = {}
for k, v in src.items():
if v == {}:
target[prefix+k] = ''
elif type(v) is dict:
_flatten(v, target, prefix + k + '/')
else:
target[prefix+k] = v
return target
target = _flatten(src)
print(target)
return target
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!")
March 12, 2024
Comments: