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