Hi, I'm trying to convert a textfile which is set out like this:

1[Tab]Hello
2[Tab]Test

into a Python dictionary how would I be able to do it?

Thanks

mydict = dict(line.strip().split('\t') for line in open('mytabfile.txt'))
print(mydict)

This prepare the dictionary with string key 1 and 2, if you want numbers as key, you must first change the keys to int and divide the job in more lines.

If you want integer keys, try this ...

# dictionary comprehension needs Python27 or higher

text = """\
1\thello
2\ttest
"""

fname = "mytest.txt"
with open(fname, "w") as fout:
    fout.write(text)

with open(fname, "r") as fin:
    d = {int(x.strip().split('\t')[0]):x.strip().split('\t')[1] for x in fin}

print(d)  # {1: 'hello', 2: 'test'}

Thanks for the help guys!

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.