trictionary?

Steven Bethard steven.bethard at gmail.com
Mon Aug 29 11:58:12 EDT 2005


mensanator at aol.com wrote:
> import csv
> temp1 = []
> temp2 = []
> reader = csv.reader(file(r"py_monsters.csv"))
> for rec in reader:
> 	temp1.append(rec)
> for i in temp1[1:]:
> 	temp2.append((i[0],dict(zip(temp1[0][1:],i[1:]))))
> monsters = dict(temp2)

I would tend to write this as:

import csv
reader = csv.reader(file(r"py_monsters.csv"))
labels = reader.next()[1:]
monsters = dict((row[0], dict(zip(labels, row[1:])))
                 for row in reader)

which I believe gives equivalent output:

py> csv_text = """\
... 
name,hardiness,agility,friend,courage,room,weight,special_def_odds,armor,weapon,odds,dice,side,hits,reaction,desc
... PIRATE,5,20,0,10,26,300,0,0,11,60,1,10,0,"not met",You see a man 
with a beard and a brass ring in his ear.  He is wearing clothes  made 
of silk and is wielding a very fancily engraved sword."""
py> f = StringIO.StringIO(csv_text)
py> reader = csv.reader(f)
py> labels = reader.next()[1:]
py> monsters = dict((row[0], dict(zip(labels, row[1:])))
...                 for row in reader)
py> monsters
{'PIRATE': {'reaction': 'not met', 'agility': '20', 'room': '26', 
'weight': '300', 'armor': '0', 'weapon': '11', 'hits': '0', 'side': 
'10', 'special_def_odds': '0', 'courage': '10', 'hardiness': '5', 
'desc': 'You see a man with a beard and a brass ring in his ear.  He is 
wearing clothes  made of silk and is wielding a very fancily engraved 
sword.', 'odds': '60', 'friend': '0', 'dice': '1'}}

STeVe



More information about the Python-list mailing list