Let’s say you receive a list of 2 linked items having a “is included in” relation. For example, you receive this list :
1 2 3 4 5 6 7 8 9 10 11 |
[('cpqswccmibrev', 'cpqswcc'), ('cpqswccfibredevstate', 'cpqswccfibre'), ('cpqswccemudev', 'cpqswcc'), ('cpqswccmibrevmajor', 'cpqswccmibrev'), ('cpqswcc', 'compaq'), ('cpqswccmibcondition', 'cpqswccmibrev'), ('cpqswccfibredevname', 'cpqswccfibre'), ('cpqswccfibre', 'cpqswcc'), ('cpqswccfibreeventdescription', 'cpqswccfibre'), ('cpqswccmibrevminor', 'cpqswccmibrev'), ('cpqswcckzpcc', 'cpqswcc')] |
Here (‘cpqswcc’, ‘compaq’) means ‘cpqswcc’ is included in ‘compaq’. You may want to build a relation tree like this :
1 2 3 4 5 6 7 8 |
{ 'compaq': { 'cpqswcc': { 'cpqswccemudev': 0, 'cpqswccfibre': { 'cpqswccfibredevname': 0, 'cpqswccfibredevstate': 0, 'cpqswccfibreeventdescription': 0}, 'cpqswcckzpcc': 0, 'cpqswccmibrev': { 'cpqswccmibcondition': 0, 'cpqswccmibrevmajor': 0, 'cpqswccmibrevminor': 0}}}} |
The cool function to do that would be the one in this code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
import pprint pp = pprint.PrettyPrinter(indent=4) def isincludedin_to_tree(item_list): out = {} index = {} for k,v in item_list: if v not in index and k not in index: out[v] = {k: 0} index[k] = out[v] index[v] = out elif v in index and k in index: if isinstance(index[v][v],int): index[v][v] = { k : index[k][k] } else: index[v][v][k] = index[k][k] to_del = index[k] index[k] = index[v][v] del to_del[k] elif v in index: dct = index[v] if isinstance(dct[v],int): dct[v] = {k: 0} index[k] = dct[v] else: dct[v].update({k: 0}) index[k] = dct[v] else: dct = index[k] out.update({v:{k:dct[k]}}) index[v] = out index[k] = out[v] del out[k] return out in_list = [('cpqswccmibrev', 'cpqswcc'), ('cpqswccfibredevstate', 'cpqswccfibre'), ('cpqswccemudev', 'cpqswcc'), ('cpqswccmibrevmajor', 'cpqswccmibrev'), ('cpqswcc', 'compaq'), ('cpqswccmibcondition', 'cpqswccmibrev'), ('cpqswccfibredevname', 'cpqswccfibre'), ('cpqswccfibre', 'cpqswcc'), ('cpqswccfibreeventdescription', 'cpqswccfibre'), ('cpqswccmibrevminor', 'cpqswccmibrev'), ('cpqswcckzpcc', 'cpqswcc')] out_dict = isincludedin_to_tree(in_list) pp.pprint(out_dict) |