Alex Rivera | Logout

How do I create a dictionary from two parallel strings?

Asked 2012-08-12T00:55:08.710
8

I have two text files, which are formatted like so:

foo,bar,etc

the other one is like this:

1,2,3

and I want to put these two text files into one dictionary for Python without having to do each one by hand. I want the output to connect the strings to the numbers. Is there any way of doing this?

Edit
Report

1 Answer

6

Assuming you know how to read the data from the file and split the lines into list, and convert them to ints as necessary.

s1 = ['foo', 'bar', 'etc']
n1 = [1, 2, 3]
dict(zip(s1, n1))

yields:

{'bar': 2, 'etc': 3, 'foo': 1}

Notes:

zip() combines your lists:

zip(s1, n1)
[('foo', 1), ('bar', 2), ('etc', 3)]

In case you are not comfortable with creating lists from your lines data, for a given line using split() you can just do

line = line.split(',') #'foo,bar,etc' => ['foo','bar','etc'] / '1,2,3' => ['1','2','3']

and if you want to convert your numeric data to ints use list comprehension:

n1 = [int(n) for n in line] # ['1','2','3'] => [1, 2, 3]
answered 2012-08-12T00:56:48.597

Your Answer