I have a dictionary where record values can refer to another record by key, eventually ending up without a record for the current value or when "-" is encountered. The purpose of this data structure is to find the parent for each record, as well as convert “-” to “No”. For example, take:
d = {'1': '-', '0': '6', '3': '1', '2': '3', '4': '5', '6': '9'}
- '1' is the root that maps to '-', so it must be set to None.
- '0' has the parent element '6', which has the parent element '9', so it should result in "9".
- '3' has a parent element '1' that maps to '-', so it should be set to None.
- '2' has a parent element '3', which has a parent element '1' that maps to '-', so it must be set to None.
- '4' must stay with parent '5'
- '6' must stay with parent '9'
My detailed 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)
Conclusion:
{'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. Element "1" does not have a parent element, and element "2" / "3" points to "1". They also should not have a parent.
Is there a puerto pythonic way to accomplish this with Python 3+?