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

Invert different types of dictionaries with mixed data types as values.

Python, 14 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def invert1(d):
    dd = {}
    for k, v in d.items():
        if not isinstance(v, (tuple, list)): v = [v]
        dd.update( [(vv, dd.setdefault(vv, []) + [k]) for vv in v] )
    return dd


def invert2(d):
    dd = {}
    for k, v in d.items():
        if not isinstance(v, (tuple, list)): v = [v]
        [dd.setdefault(vv, []).append(k) for vv in v]
    return dd

I just wanted to add a few more possibilities to the inverters in these recipes: <pre> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252143 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/415100 </pre> The difference between these two can be seen using {'A': [1, 1]}: <pre> invert1({'A': [1, 1]}) --> {1: ['A']} invert2({'A': [1, 1]}) --> {1: ['A', 'A']} </pre> You can try it out with these as well: <pre> {'A': (1,), 'C': (3, 3), 'B': (2, 4)} {'A': [3, 2, 1], 'C': [3, 2], 'B': [1, 4]} {'A': 2, 'C': 4, 'B': 5, 'D': 5} {'A': 2, 'C': 4, 'B': 5, 'D': [5, 3]} {'A': [1, 2, 3], 'B': 4} </pre>

Created by Jonathan Knoll on Tue, 11 Jul 2006 (PSF)
Python recipes (4591)
Jonathan Knoll's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks