[Tutor] looping through and comparing lists of dictionaries
Bruce Dykes
Bruce Dykes" <bkd@graphnet.com
Wed Apr 23 09:01:40 2003
----- Original Message -----
From: "Don Arnold" <darnold02@sprynet.com>
To: "bkd" <bkd@graphnet.com>; <tutor@python.org>
Sent: Wednesday, April 23, 2003 07:00
Subject: Re: [Tutor] looping through and comparing lists of dictionaries
> Why not just check the old hair color before adding to the redheads list?
>
> redheads = []
>
> for newgirl in newdata:
> if newgirl['hair'] == 'Redhead':
> for oldgirl in olddata:
> if oldgirl['name'] == newgirl['name']:
> if oldgirl['hair'] != 'Redhead':
> print '%s used to be a %s' % (newgirl['name'],
> oldgirl['hair'])
> redheads.append(newgirl)
> break
>
> print redheads
>
> --output--
>
> Betty used to be a Blonde
> Veronica used to be a Brunette
> Samantha used to be a Blond
> [{'hair': 'Redhead', 'role': 'Student', 'name': 'Betty'}, {'hair':
> 'Redhead', 'role': 'Student', 'name': 'Veronica'}, {'hair': 'Redhead',
> 'role': 'Witch', 'name': 'Samantha'}]
>
> --end output--
I was thinking that might take too long, but I didn't realize the second
loop would *only* be called if the test for Redheadedness was true...I first
thought I would be iterating through the old list for every entry in the new
list, so I thought to go with creating the list of Redheads first, and using
that as the check.
But then, the big timesink in this script is the telnet session.
Mucho thanks.
> Also, since Python's for statement iterates over a collection, it's often
> cleaner to iterate directly over your list/tuple instead of using range( )
> and then indexing into it.
When I was first starting with Python, that didn't work in some of my
scripts, while the range(len()) construct did, so that's just a habit I've
since fallen into...
Bruce