faqts : Computers : Programming : Languages : Python : Snippets : Dictionaries

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

24 of 28 people (86%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

Inverting a dictionary

Jul 5th, 2000 09:59
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 54, Guido van Rossum


"""
Packages: basic_datatypes.dictionaries
"""

"""
> Well -- there is Guido van Rossum's variant:

Here's the correct version:
"""

def invert(table):
    index = {}                           # empty dictionary
    for key in table.keys():
        value = table[key]
        if not index.has_key(value):
            index[value] = []            # empty list
        index[value].append(key) 
    return index