Sarp Kaya
Sarp Kaya

Reputation: 3794

converting a list of strings into a tuple

Hello i am trying to do a dictionary by using Python, What needs to be done is python reads a text file which has values inside such as:

good    buono

What I have done was, open the file with file function and replace tabs and add reversed comma to create a list so it looks like

["('good', 'buono')", "('afternoon', 'pomeriggo')",... and so on

but the problem is type of each word translation is not a tuple, it is string when I am trying to see 1st element(number 0) it shows me the value as

"('good', 'buono')"

which is a string. I need to use dict formula so that i can convert the type into dictionary but I cannot because it is list of strings(has to be list of tuples)

So how can I convert that list of strings into list of tuples?

Upvotes: 3

Views: 3227

Answers (3)

jfs
jfs

Reputation: 414395

with open('input.txt') as f:
     result = map(str.split, f)
     # -> [['good', 'buono'], ['afternoon', 'pomeriggo']]
     d = dict(result)
     # -> {'good': 'buono', 'afternoon': 'pomeriggo'}

Upvotes: 4

Tim Pietzcker
Tim Pietzcker

Reputation: 336238

Assuming that every pair of words is on a separate line in your file, you could do this:

mydict = {line.split()[0]: line.split()[1] for line in myfile}

This transforms a file like

good    buono
afternoon   pomeriggo
thanks    grazie

into

{"good": "buono", "afternoon": "pomeriggo", "thanks": "grazie"}

No need for tuples along the way.

.split() splits the input string on whitespace, removing any leading/trailing whitespace:

>>> "  good\tbuono  \n".split()
['good', 'buono']

Upvotes: 4

Makoto
Makoto

Reputation: 106450

ast will work as @onemach suggested, but you may want to read the strings in as tuples instead.

Snippet:

li = []
with open("file.txt", 'r') as f:
    li.append(tuple(f.readline().split('\t')))

This will split the string about the tab, and place it into a tuple object, which is then appended into a list.

Upvotes: 1

Related Questions