[Tutor] basic lists and loops question

Jon Crump jjcrump at myuw.net
Wed May 14 21:02:20 CEST 2008


Something basic about lists and loops that I'm not getting here. I've got 
a long list of dictionaries that looks like this:

lst = [{'placename': u'Stow, Lincolnshire', 'long-name': u'Stow, 
Lincolnshire.', 'end': datetime.date(1216, 9, 28), 'start': 
datetime.date(1216, 9, 26)},
{'placename': u'Lincoln, Lincolnshire', 'long-name': u'Lincoln, 
Lincolnshire.', 'end': datetime.date(1216, 9, 30), 'start': 
datetime.date(1216, 9, 28)},
{'placename': u'Lincoln, Lincolnshire', 'long-name': u'Lincoln, 
Lincolnshire.', 'end': datetime.date(1216, 10, 2), 'start': 
datetime.date(1216, 10, 1)},
{'placename': u'Grimsby, Lincolnshire', 'long-name': u'Grimsby, 
Lincolnshire.', 'end': datetime.date(1216, 10, 4), 'start': 
datetime.date(1216, 10, 3)},
{'placename': u'Louth, Lincolnshire', 'long-name': u'Louth, 
Lincolnshire.', 'end': datetime.date(1216, 10, 4), 'start': 
datetime.date(1216, 10, 4)}
]

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"

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.

Could someone explain what's going on here?

Thanks,
Jon


More information about the Tutor mailing list