Faqts : Business : Programming : Shopping For You : Python : Snippets : Dictionaries

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

29 of 35 people (83%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

Inverting a dictionary

Dec 18th, 2009 11:59
new acct, Shopping Snooper, baalu aanand, 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,value in table.items():
        if value not in index:
            index[value] = []            # empty list
        index[value].append(key) 
    return index



Here is my logic to invert the dictionary(i.e makes the key as value and
value as key of a dictionary)

orginalDic = {'fruit':'apple', 'vegetables':'carrot', 'drinks':'milk'}
l = []
for k, v in orginalDic.iteritems():
    l.append(k)
    l.append(v)

invertedDic = dict(zip(l[1::2],l[::2]))


{'carrot': 'vegetables', 'apple': 'fruit', 'milk': 'drinks'}


thanks
Baalu