python on window

Michael Bentley michael at jedimindworks.com
Mon Mar 26 15:18:55 CEST 2007


On Mar 26, 2007, at 7:00 AM, sandeep patil wrote:
> i have written this program but i have gott following error,
> in anather proram "indentation error" sir how i will indent in my
> editor
>
> #test.py
>>>> def invert(table):
> 	index=()
> 	for key in table:
> 		value=table[key]
> 		if not index.has_key(value):
> 			index[value]=[]
> 			index[value].append(key)
> 		return index
>
>
>>>> phonebook = {'sandeep':9325, 'amit':9822, 'anand':9890, 'titu':  
>>>> 9325}
>>>> phonebook
> {'titu': 9325, 'amit': 9822, 'anand': 9890, 'sandeep': 9325}
>>>> print phonebook
> {'titu': 9325, 'amit': 9822, 'anand': 9890, 'sandeep': 9325}
>>>> inverted_phonebook = invert(phonebook)
>
> Traceback (most recent call last):
>   File "<pyshell#13>", line 1, in <module>
>     inverted_phonebook = invert(phonebook)
>   File "<pyshell#9>", line 5, in invert
>     if not index.has_key(value):
> AttributeError: 'tuple' object has no attribute 'has_key'

If you define index as a dict instead of a tuple, you'll stop getting  
that error -- but I'm afraid it still won't do what you want.  Are  
you trying to get a phonebook in which the values of the original  
phonebook are the keys of the new one -- and the values are lists  
(both 'sandeep' and 'titu' have the same number)?  If so, try this:

def invert(table):
	index=dict()
	for k,v in table.items():
		if index.has_key(v):
			index[v].append(k)
		else:
			index[v] = [k]
	return index

You had mentioned something about indentation error...  If you'll  
look at your definition of invert(), you can see that 'return index'  
is inside the for loop -- which would cause a return before the  
second time through the for loop.  By dedenting (is that a word?) so  
'return' falls directly below 'for', the for loop would have been  
able to run to completion before returning.

Hope this helps,
Michael

---

Our network was brought down by a biscuit??? --Steven D'Aprano






More information about the Python-list mailing list