MAS
MAS

Reputation: 4993

reading key and values into python dict from text

I have a text file in this format.

the 0.418 0.24968 -0.41242 0.1217 0.34527 -0.044457 -0.49688 -0.17862 -0.00066023 -0.6566 0.27843 -0.14767 -0.55677 0.14658 -0.0095095 0.011658
and 0.26818 0.14346 -0.27877 0.016257 0.11384 0.69923 -0.51332 -0.47368 -0.33075 -0.13834 0.2702 0.30938 -0.45012 -0.4127 -0.09932 0.038085 

I want to read it into a python dict variable such that I have

{'the': [0.418, 0.24968,..], 'and': [0.26818 0.14346,..]}

I am not sure how to start?

Upvotes: 1

Views: 70

Answers (3)

user6058549
user6058549

Reputation:

Is this a start?

import json

variable_one = "the 0.418 0.24968 -0.41242 0.1217 0.34527 -0.044457 -0.49688 -0.17862 -0.00066023 -0.6566 0.27843 -0.14767 -0.55677 0.14658 -0.0095095 0.011658"

variable_one = variable_one.split()
json_variable_one = []
json_variable_one = variable_one[0], variable_one[1:]

print(json.dumps(json_variable_one))

output:

["the", ["0.418", "0.24968", "-0.41242", "0.1217", "0.34527", "-0.044457", "-0.49688", "-0.17862", "-0.00066023", "-0.6566", "0.27843", "-0.14767", "-0.55677", "0.14658", "-0.0095095", "0.011658"]]

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117856

You can iterate over the file line by line. Then split on whitespace, use the index [0] as the key, then use a list comprehension to convert the remaining values to a list of float.

with open(text_file) as f:
    d = dict()
    for line in f:
        data = line.split()
        d[data[0]] = [float(i) for i in data[1:]]
    print(d)

Output

{'and': [0.26818, 0.14346, -0.27877, 0.016257, 0.11384, 0.69923, -0.51332, -0.47368, -0.33075, -0.13834, 0.2702, 0.30938, -0.45012, -0.4127, -0.09932, 0.038085],
 'the': [0.418, 0.24968, -0.41242, 0.1217, 0.34527, -0.044457, -0.49688, -0.17862, -0.00066023, -0.6566, 0.27843, -0.14767, -0.55677, 0.14658, -0.0095095, 0.011658]}

Upvotes: 1

DevShark
DevShark

Reputation: 9112

Here's a solution that works:

my_dict = {}
with open('your_file_name') as f:
    for line in f:
        elements = line.split()
        my_dict[elements[0]] = [float(e) for e in elements[1:]]

Note that the solution suggested by @CoryKramer uses readlines, which returns a list and not an iterator. So I would not recommend using his solution for large files (it will take too much memory unnecessarily).

Upvotes: 1

Related Questions