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?
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.
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(',')]
Assuming you know how to read the data from the file and split the lines into list, and convert them to int
s 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 int
s use list comprehension:
n1 = [int(n) for n in line] # ['1','2','3'] => [1, 2, 3]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With