I have a dictionary where entry values can reference another entry by key eventually ending with no entry for the current value or when “-” is encountered. The goal of this data structure is to find the parent for each entry and also transform “-” into None. For instance take:
d = {'1': '-', '0': '6', '3': '1', '2': '3', '4': '5', '6': '9'}
- ‘1’ is a root that maps to ‘-‘ so it should result in None.
- ‘0’ has a parent of ‘6’, which has a parent of ‘9’ so it should result in ‘9’.
- ‘3’ has a parent of ‘1’, which maps to ‘-‘ so it should result in None.
- ‘2’ has a parent of ‘3’,which has a parent of ‘1’ which maps to ‘-‘ so it should result in None.
- ‘4’ should remain with parent of ‘5’
- ‘6’ should remain with parent of ‘9’
My verbose solution is as follows:
d = {'1': '-', '0': '6', '3': '1', '2': '3', '4': '5', '6': '9'}
print(d)
for dis, rep in d.items():
if rep == "-":
d[dis] = None
continue
while rep in d:
rep = d[rep]
if rep == "-":
d[dis] = None
break
else:
d[dis] = rep
print(d)
The output is:
{'1': '-', '0': '6', '3': '1', '2': '3', '4': '5', '6': '9'}
{'1': None, '0': '9', '3': None, '2': None, '4': '5', '6': '9'}
The result is correct. The “1” element has no parent and the “2”/”3″ element point back to “1”. They should also have no parent.
Is there a terser pythonic way to accomplish this using Python 3+?
To “walk” the dictionary, just do the lookups in a loop until there are no more: