[Tutor] get as a way to operate on first occurrence of an element in a list?

Alan Gauld alan.gauld@blueyonder.co.uk
Sun Aug 3 04:57:02 EDT 2003


> for line in f:
>     if line in seen_dict:
>         pass
>     else:
>         print line,
>         seen_dict[line] = 1

IMHO Its better to let the test rewflect what you want 
rather than what you don't want...

if line not in seen_dict:
   print line
   seen_dict[line] = 1


Is there a way to use get to test for a value, fail if 
it doesn't exist, and *then* assign a value to it? 

NOpe, the whole point of get is that it fetches a value 
from the dictionary if it exists and returns the default 
if it doesn't. So it never fails. Its a get() not a set()...

>>> d = {}
>>> d.get(1,2)
2
>>> d[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 1
>>>

Notice although it gave me a value back for key 1 it 
did NOT create an entry for key 1 in d.

it's equivalent to:

def get(key, default)
  if key in d:
    return d[key]
  else: return default

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list