This takes a dictionary and reverses it so the that the integers in the value lists become the keys and the original keys are appended to value lists.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def getReverseConnectivity(connectivity):
"""getReverseConnectivity(connectivity) -->
resort connectivity dict with nodes as keys"""
reverseConnectivity = {}
for el, conn in connectivity.items():
for node in conn:
if node not in reverseConnectivity.keys():
reverseConnectivity[node]=[el,]
else:
reverseConnectivity[node].append(el)
return reverseConnectivity
>>> sc = {70: [156, 159, 158, 155], 69: [155, 158, 157, 154], 68: [153, 156, 155, 152], 67: [152, 155, 154, 151]}
>>> getReverseConnectivity(sc)
{159: [70], 158: [70, 69], 157: [69], 156: [70, 68], 155: [70, 69, 68, 67], 154: [69, 67], 153: [68], 152: [68, 67], 151: [67]}
|
I use it in a Finite Element post-processing script to find neighbouring elements with the element connectivity (element label as key and node labels as values) as the input (returning nodeLabel as keys, and list of elementLabels sharing the same node).
Any suggestions for speeding this up? Thanks James
shorter (maybe faster). This version might be faster, it is shorter to write
Regards Berthold
Micro-optimization. In addition, you can factor out the lookup for the setdefault method.