Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a dictionary from two parallel strings?

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?

like image 940
Ekansh Vinaik Avatar asked Aug 12 '12 00:08

Ekansh Vinaik


People also ask

How do you create a dictionary with two sets?

Method #1: Naive Method The basic method that can be applied to perform this task is the brute force method to achieve this. For this, simply declare a dictionary, and then run nested loop for both the lists and assign key and value pairs from list values to dictionary.


3 Answers

keys = first_string.split(',')
values = second_string.split(',')
output_dict = dict(zip(keys, values))

>>> first_string = "foo,bar,etc"
>>> second_string = "1,2,3"
>>> keys = first_string.split(',')
>>> values = second_string.split(',')
>>> output_dict = dict(zip(keys, values))
>>> output_dict
{'etc': '3', 'foo': '1', 'bar': '2'}

If you want the values to be actual numbers, you can convert them:

values = [int(v) for v in second_string.split(',')]
like image 130
Amber Avatar answered Oct 30 '22 10:10

Amber


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]
like image 35
Levon Avatar answered Oct 30 '22 11:10

Levon


You can read the values and keys directly from the text files, a sample code would be :

import fileinput

keys = []
values = []

for line in fileinput.input(['v.txt']):
    values = values + [int(v) for v in line.split(',')]

for line in fileinput.input(['k.txt']):
    keys = keys + [k.replace("\n","") for k in line.split(',')]

the_dict = dict(zip(keys, values))

I assume that you need the values as integers, and the text files may contain multiple lines but they must contain the same number of elements.

like image 36
Ilyas Avatar answered Oct 30 '22 11:10

Ilyas