How to create a dictionary of two parallel lines?

I have two text files that are formatted like this:

foo,bar,etc

another is as follows:

1,2,3

and I want to put these two text files in one dictionary for Python without having to do each of them manually. I want the output to connect strings with numbers. Is there any way to do this?

+5
source share
4 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 real numbers, you can convert them:

values = [int(v) for v in second_string.split(',')]
+10
source

Assuming you know how to read data from the file and line breaks in the list, and convert them intas required.

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

gives:

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

Notes:

zip () concatenates your lists:

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

, split()

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

int, :

n1 = [int(n) for n in line] # ['1','2','3'] => [1, 2, 3]
+5

You can read values ​​and keys directly from text files, example code:

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 values ​​as integers, and text files can contain multiple lines, but they should contain the same number of elements.

+1
source

I am just starting, but it would be easier to just run them together on the same line:

string_dict = {'etc': '3', 'foo': '1', 'bar': '2'}
0
source

All Articles