I try to expand the values of a dictionary using keys in the same dictionary. In other words, I try to replace dic values (existing set with another/ potentially expanded set). The expansion happens when the value contains a key in the dictionary.
Input:
dic = {
'10': {'01', '02'},
'11': {'03', '04'},
'20': {'05', '10'},
'21': {'06', '11'},
'30': {'07', '20'},
'40': {'08', '21', '30'},
'50': {'09', '40'}
}
Expected output:
{
'10': {'01', '02'},
'11': {'03', '04'},
'20': {'05', '01', '02'},
'21': {'06', '03', '04'},
'30': {'07', '05', '01', '02'},
'40': {'08', '06', '03', '04', '07', '05', '01', '02'},
'50': {'09', '08', '06', '03', '04', '07', '05', '01', '02'}
}
I was trying to create a recursive function...
def transform_dic(d):
def func(k):
v = d.get(k, k)
if v != k:
for e in v:
v = func(v)
return v
d2 = {}
for k, v in d.items():
d2[k] = {func(i) for i in v}
return d2
print(transform_dic(dic))
TypeError: unhashable type: 'set'