First, this post is a solution not using generators: Flatten dictionary of dictionaries
I have a dictionary of dictionaries.
For example:
{
"name": {
"first": "One",
"last": "Drone"
},
"job": "scout",
"recent": {},
"additional": {
"place": {
"zone": "1",
"cell": "2"}
}
}
The result will be:
{"name/first": "One", #one parent
"name/last": "Drone",
"job": "scout", #root key
"recent": "", #empty dict
"additional/place/zone": "1", #third level
"additional/place/cell": "2"}
I tried solving it differently and the keys just won't return if you could help me figuring how to use the recursion over there.. By the way this is an exercise from checkio.org
def flatten(a):
arr = flatten_dictionary(a)
newDict = {}
for i in arr:
temp = i.split(':')
try:
newDict[temp[0]]=temp[1]
except:
pass
return newDict
def flatten_dictionary(a):
for i in a:
if isinstance(a[i],type(dict)):
yield from(i+'/' + flatten(a[i])) #won't enter this if scope
else:
yield ':'+a[i]
Here are some asserts if you want to test it..
assert flatten({"key": "value"}) == {"key": "value"}, "Simple"
assert flatten(
{"key": {"deeper": {"more": {"enough": "value"}}}}
) == {"key/deeper/more/enough": "value"}, "Nested"
assert flatten({"empty": {}}) == {"empty": ""}, "Empty value"
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"}
Also, right now this is my result: {"":"value"}