How can I re-factorise this circular nesting dictionary function?
The challenge:
I recently received a data extract with a list of folder names and associated subfolders. The challenge was to produce a reusable function that could provide a summary of the unique folder names and all the nested subfolders.
The data source was an excel spreadsheet containing 2 columns:
Parent: Folder name
Child: Subfolder name
Note: I have recreated spreadsheet data using pandas so the code can be easily tested.
Create table:
import pandas as pd
data = {'Parent': ['A', 'B', 'C', 'D', 'E', 'F', 'C', 'C'],
'Child': ['B', 'C', 'E', 'E', 'Z', 'Z', 'B', 'A']}
df = pd.DataFrame(data)
print(df):
Parent Child
0 A B
1 B C
2 C E
3 D E
4 E Z
5 F Z
6 C B
7 C A
My solution:
def relationship_dictionary(dataframe, key_column_name, values_column_name):
"""
The key_column_name is the primary data source that should be considered the
start of the nested relationship.
The values_column_name is the subfolder
Creates a dictionary of unique relationships to each key.
"""
parent = key_column_name
child = values_column_name
d = {}
for i, row in dataframe.iterrows():
key = row[parent]
value = row[child]
if key in d.keys():
d[key].append(value)
else:
d[key] = [value]
for k, values in d.items():
for v in values:
if v in d.keys():
for each in d[v]:
if (each not in d[k]) and (each != k):
d[k].extend([each])
return d
Result:
relationship_dictionary(df, "Parent", "Child")
{'A': ['B', 'C', 'E', 'Z'],
'B': ['C', 'E', 'A', 'Z'],
'C': ['E', 'B', 'A', 'Z'],
'D': ['E', 'Z'],
'E': ['Z'],
'F': ['Z']}
Feedback
I'm happy to say it works after mitigating the circular nesting issue but I can't help thinking there is a far simpler way of doing this so I thought I'd put it out there for critique so feedback would be welcome... :)