[Tutor] looping through and comparing lists of dictionaries

Jayprasad J. Hegde jjhegde@ncst.ernet.in
Sun Apr 27 05:34:02 2003


On Wed, Apr 23, 2003 at 04:41:46PM +0200, Michael Janssen wrote:
Smart solution Michael. 

Just to share the spoils, I would like to include a solution which
uses the list version too and is perhaps a bit more elegant (modesty,
modesty, where art thou? ;) )

This solution simply gathers the list of 'oldtimers' having the
desired feature -- in this case the hair colour -- and makes a list
out of it.  It then appends a girl's name to the new list only if she
is not there on the old list.

I hope you folks finds it useful. 

Sayonara,
- JJH
ps - Here it is: 

redheads = []
oldtimers = []
reqdColour = 'Redhead'
for girl in olddata:
    if girl ['hair'] == reqdColour:
        oldtimers.append (girl ['name'])
## print oldtimers

for girl in newdata:
    if girl['hair'] == reqdColour:
        if girl ['name'] not in oldtimers:
            redheads.append (girl ['name'])
print redheads


> ------------ Michael's solution ------------------
> 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'])
> 
-- 
BOFH excuse #262:
Our POP server was kidnapped by a weasel.
[ Jayprasad J. Hegde, KBCS Division, National Centre for
Software Technology, Juhu, Mumbai 400049, India. Tel:+91-22-26201606x373 ]