Welcome, guest | Sign In | My Account | Store | Cart

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.

Python, 17 lines
 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

2 comments

Berthold Höllmann 19 years, 1 month ago  # | flag

shorter (maybe faster). This version might be faster, it is shorter to write

def getReverseConnectivity(connectivity):
    """getReverseConnectivity(connectivity) -->
       resort connectivity dict with nodes as keys"""
    reverseConnectivity = {}
    for el, conn in connectivity.items():
        for node in conn:
            reverseConnectivity.setdefault(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]}
print getReverseConnectivity(sc)

Regards Berthold

Raymond Hettinger 19 years, 1 month ago  # | flag

Micro-optimization. In addition, you can factor out the lookup for the setdefault method.

def getReverseConnectivity2(connectivity):
    """getReverseConnectivity(connectivity) -->
       resort connectivity dict with nodes as keys"""
    reverseConnectivity = {}
    setdef = reverseConnectivity.setdefault
    for el, conn in connectivity.items():
        for node in conn:
            setdef(node, []).append(el)
    return reverseConnectivity
Created by James Lockley on Tue, 20 Apr 2004 (PSF)
Python recipes (4591)
James Lockley's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks