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

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

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.