[Tutor] looping through and comparing lists of dictionaries
Michael Janssen
Janssen@rz.uni-frankfurt.de
Wed Apr 23 10:54:02 2003
On Wed, 23 Apr 2003, bkd wrote:
> But this breaks with an 'index out of range' error. The lesson being, do not
> mess with the list you're indexing over, make a copy and mess with the copy.
>
> But still, I can't help but think there must be a better way to do this. Any
> suggestions where I should look first? Learning Python and the online
> documentation seem fairly anemic when it comes to showing how to really
> wield dictionaries with power, and the Python Cookbook seems to assume one
> has a bit more knowledge about the language than the bundled docs provide...
cool, it works: people does learn things like not manipulate lists while
iterating about :-)
Beside what Don Arnold have already contributed:
Why store the dicts into a list? Lists are used when order must be
maintained or you want to sort (and it is not simple to sort a list of
dict). If both aspects don't occour, you should use a dict of dict. This
way you gain much easier lookups:
olddata={'Betty': {'hair':'Blonde','role':'Student'},
'Veronica': {'hair':'Brunette','role':'Student'},
'Maryann': {'hair':'Brunette','role':'Castaway'},
'Ginger': {'hair':'Redhead','role':'Castaway'},
'Jeanne': {'hair':'Blond','role':'Genie'},
'Serena': {'hair':'Brunette','role':'Genie'},
'Samantha': {'hair':'Blond','role':'Witch'},
}
and the same for nowdata
new_redhead = []
for name in newdata.keys():
if newdata[name]['hair'] == 'Redhead' and \
olddata[name]['hair'] != 'Redhead':
new_redhead.append(name)
in case your data comes indeed sorted-by-name and you want maintain the
order with a list, it's even more simple:
for old, new in zip(olddata, newdata):
if new['hair'] == 'Redhead' and \
olddata['hair'] != 'Redhead':
new_redhead.append(new['name'])
Michael
>