[Tutor] basic lists and loops question

Kent Johnson kent37 at tds.net
Wed May 14 23:31:04 CEST 2008


On Wed, May 14, 2008 at 3:02 PM, Jon Crump <jjcrump at myuw.net> wrote:
> Something basic about lists and loops that I'm not getting here.
>  I have a function that searches through them to find pairs of dictionaries
> that satisfy certain criteria. When the nested loops find such a pair, I
> need to merge them. So far so good. This works:
>
>  def events(data):
>   evts = []
>   for x in lst:
>     for y in lst:
>       if (x['placename'] == y['placename']) and (x['end'].month + 1 ==
> y['start'].month) and (y['start'] - x['end'] == datetime.timedelta(1)):
>         evts.append({'placename': x['placename'], 'long-name':
> x['long-name'], 'start': x['start'], 'end': y['end']})
>     evts.append(x)
>   return evts
>
>  for x in events(lst):
>   print x
>
>  But then I need to delete the two original dictionaries that I merged. If I
> do del x, I get an error "local variable 'x' referenced before assignment"

Not sure why you got that error but it general it is not a good idea
to delete items from a container you are iterating; the results can be
unpredictable.
>
>  I've also tried decorating the processed dictionaries in the if loop thus:
>  x['processed'] = True
>  y['processed'] = True
>
>  Then when I call events() I get back the merged dict and the decorated
> dicts:
>
>  {'placename': u'Lincoln, Lincolnshire', 'end': datetime.date(1216, 10, 2),
> 'start': datetime.date(1216, 9, 28), 'long-name': u'Lincoln, Lincolnshire.'}
>  {'placename': u'Lincoln, Lincolnshire', 'processed': True, 'end':
> datetime.date(1216, 9, 30), 'start': datetime.date(1216, 9, 28),
> 'long-name': u'Lincoln, Lincolnshire.'}
>  {'placename': u'Lincoln, Lincolnshire', 'processed': True, 'end':
> datetime.date(1216, 10, 2), 'start': datetime.date(1216, 10, 1),
> 'long-name': u'Lincoln, Lincolnshire.'}
>
>  But if I try to call events() thus:
>
>  for x in events(lst):
>   if x['processed'] == True:
>     print x
>
>  I get a KeyError.

The problem is that not every dict has the 'processed' key. Try
  if x.get('processed') == True:
or just
  if x.get('processed'):

x.get() will return None (instead of raising KeyError) if the key is
not present.

Kent


More information about the Tutor mailing list