0

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

3
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by ineedhelpasap
0
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.

Edited by pyTony: n/a

3

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'}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.