I have a text file that contains Road Name types paired with their abbreviated form.

For example:
...
Avenue,Av
Road,Rd
South East,SE
Terrace,Tce
...

How do I a create a dictionary variable from this CSV file in python 2.5.1 so I can get it in this form?

{...'Avenue': 'Av', 'Road': 'Rd', 'South East': 'SE', 'Terrace': 'Tce'...}

Would csv.DictWriter do the job?

Regards

Attachments
Access,Accs
Alley,Ally
Alleyway,Alwy
Amble,Ambl
Approach,App
Arcade,Arc
Arterial,Artl
Avenue,Av
Banan,Ba
Bend,Bend
Boardwalk,Bwlk
Boulevard,Bvd
Boulevarde,Bvd
Brae,Brae
Break,Brk
Brow,Brow
Bypass,Bypa
Byway,Bywy
Causeway,Cswy
Central,Cn
Centre,Ctr
Chase,Ch
Circle,Cir
Circuit,Cct
Circus,Crcs
Close,Cl
Concourse,Con
Copse,Cps
Corner,Cnr
Court,Ct
Courtyard,Ctyd
Cove,Cove
Crescent,Cr
Crest,Crst
Cross,Crss
Cul-De-Sac,Csac
Cutting,Cutt
Dale,Dale
Dip,Dip
Drive,Dr
Driveway,Dvwy
East,E
Edge,Edge
Elbow,Elb
End,End
Entrance,Ent
Esplanade,Esp
Expressway,Exp
Extension,Ex
Fairway,Fawy
Follow,Folw
Footway,Ftwy
Formation,Form
Freeway,Fwy
Frontage,Frtg
Gap,Gap
Gardens,Gdns
Gate,Gte
Glade,Glde
Glen,Glen
Grange,Gra
Green,Grn
Grove,Gr
Heights,Hts
Highroad,Hird
Highway,Hwy
Hill,Hill
Interchange,Intg
Junction,Jnc
Key,Key
Lane,Lane
Laneway,Lnwy
Line,Line
Link,Link
Lookout,Lkt
Lower,Lr
Mall,Mall
Meander,Mndr
Mews,Mews
Motorway,Mtwy
Nook,Nook
North East,NE
North West,NW
North,N
Outlook,Otlk
Parade,Pde
Parkway,Pwy
Pass,Pass
Passage,Psge
Path,Path
Pathway,Pway
Piazza,Piaz
Place,Pl
Plaza,Plza
Pocket,Pkt
Point,Pnt
Port,Port
Promenade,Prom
Quadrant,Qdrt
Quays,Qys
Ramble,Rmbl
Rest,Rest
Retreat,Rtt
Ridge,Rdge
Rise,Rise
Road,Rd
Rotary,Rty
Route,Rte
Row,Row
Rue,Rue
Serviceway,Svwy
Shunt,Shun
South East,SE
South West,SW
South,S
Spur,Spur
Square,Sq
Street,St
Subway,Sbwy
Tarn,Tarn
Terrace,Tce
Thoroughfare,Thfr
Tollway,Tlwy
Top,Top
Tor,Tor
Track,Trk
Trail,Trl
Turn,Turn
Upper,Up
Vale,Vale
Viaduct,Viad
View,View
Vista,Vsta
Walk,Walk
Walkway,Wkwy
Way,Way
West,W
Wharf,Whrf
Wynd,Wynd

I have a text file that contains Road Name types paired with their abbreviated form.

For example:
...
Avenue,Av
Road,Rd
South East,SE
Terrace,Tce
...

How do I a create a dictionary variable from this CSV file in python 2.5.1 so I can get it in this form?

{...'Avenue': 'Av', 'Road': 'Rd', 'South East': 'SE', 'Terrace': 'Tce'...}

Would csv.DictWriter do the job?

Regards

After a bit of research, I believe I have a solution.

f=open("txtfile.txt")
for line in f:
     a,b=map( str, line.split(','))
     d[a]=b.strip('\n')
f.close()
print d

Alternative solutions still welcome

Edited 6 Years Ago by gangemia: n/a

2 more solutions using dict()

datas="""Avenue,Av
Road,Rd
South East,SE
Terrace,Tce""".split("\n")

# The shortest way :
print dict([(l.split(",")[0], l.split(",")[1]) for l in datas])

# a more understandable way
lst=[]
for l in datas:
    sl=l.split(",")
    lst.append((sl[0], sl[1]))
d=dict(lst)
print d

Edited 6 Years Ago by jice: n/a

This question has already been answered. Start a new discussion instead.