The Python Programming Language

Invert a Table Example Program


Click below to go directly to a specific section:
Description| Source Code| Sample Run

Description

This function will invert a table (represented as a Python dictionary).

Source Code


>>> 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


Sample Run


>>> phonebook() = {'guido': 4127, 'sjoerd': 4127, 'jack' : 4098}
>>> phonebook['dcab'] = 4147
>>> inverted_phonebook = invert(phonebook)
>>> print inverted_phonebook
{ 4098: ['jack'], 4127: ['guido', 'sjoerd'], 4147: ['dcab'] }


[Back] [Home]

Last modified: 5:00 PM on 12/09/1997