I`m trying to solve an exercise by using python and i think i solved it. When i run single test with my function it works well. But when its multiple checks i got errors. Every function saving results to the same dictionary. I tried to read about visibility of variables but i got nothing. Please give me a link where can i read about this topic.
def flatten(dicts, a='', free={}):
for k, v in dicts.iteritems():
if a in dicts.keys():
a = ""
if a != "":
b = "/"
else:
b = ""
if isinstance(v, dict):
if len(v.keys()) == 0:
free[a+b+k] = ""
else:
a += b+k
flatten(v, a)
else:
free[a+b+k] = v
return free
print flatten({"key": "value"}) == {"key": "value"}
print flatten({"key": {"deeper": {"more": {"enough": "value"}}}}) == {"key/deeper/more/enough": "value"}
print 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"}
I got this in the end:
{'key/deeper/more/enough': 'value', 'additional/place/zone': '1',
'job': 'scout', 'additional/place/cell': '2', 'name/first': 'One',
'name/last': 'Drone', 'key': 'value', 'recent': ''}