Sanjay
Sanjay

Reputation: 55

python file to dictionary

I have a slightly different problem than the previous questions asked on this topic. Text file has the following contents

x1 x2 x3 gh3 tf2
0.1 0.7 0.8 0.9 8.9
y1 ft gt hh
2 4 7 8
.
.
.

I would like to add this to a dictionary , so has key: value x1:0.1 and so on.

this is what I have now and it doesnt really work for me

ned = {}
nel =[]
with open('test.dat', 'r') as f:
    for line in f:
        splitline= line.split()
        print(splitline)
        ned[int(splitline[0])] = ",".join(splitline[1:])

Upvotes: 0

Views: 76

Answers (5)

Martin Evans
Martin Evans

Reputation: 46759

The following reads your file in two lines at a time and uses a dictionary comprehension to create a per 2-row dictionary to update my_dict with:

my_dict = {}

with open('test.dat') as f_input:
    for l1, l2 in zip(*[iter(f_input)] * 2):
        my_dict.update({k: v for k, v in zip(l1.split(), l2.split())})

print(my_dict)

Giving you:

{'gt': '7', 'ft': '4', 'gh3': '0.9', 'y1': '2', 'hh': '8', 'x2': '0.7', 'x3': '0.8', 'x1': '0.1', 'tf2': '8.9'}

To convert all the values to floats, change the update to:

my_dict.update({k: float(v) for k, v in zip(l1.split(), l2.split())})

Giving you:

{'gh3': 0.9, 'tf2': 8.9, 'x3': 0.8, 'gt': 7.0, 'y1': 2.0, 'x1': 0.1, 'ft': 4.0, 'hh': 8.0, 'x2': 0.7}

Upvotes: 0

Valentin B.
Valentin B.

Reputation: 622

lines_read = []
with open("test.dat", "r") as f:
    lines_read = f.readlines()

key_line = []
value_line = []
out_dict = {}
for i, line in enumerate(lines_read):
    if i % 2 == 0:
        key_line = line.strip().split()
    else:
        value_line = line.strip().split()
        out_dict.update(dict(zip(key_line, value_line)))

For conciseness, and if you do not care so much about writing explicit code you could do without the list initializations:

with open("test.dat", "r") as f:
    lines_read = f.readlines()

out_dict = {}
for i, line in enumerate(lines_read):
    if i % 2 == 0:
        key_line = line.strip().split()
    else:
        value_line = line.strip().split()
        out_dict.update(dict(zip(key_line, value_line)))

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71451

You can try this:

data = [i.strip('\n').split() for i in open('filename.txt')]
new_data = [{b[i]:b[i+1] for i in range(0, len(b), 2)} for b in zip(*data)]
final_dict = {}
for i in new_data:
   final_dict.update(i)

Output:

{'x1': '0.1', 'ft': '4', 'gt': '7', 'gh3': '0.9', 'y1': '2', 'hh': '8', 'x2': '0.7', 'x3': '0.8',...}

Upvotes: 0

stamaimer
stamaimer

Reputation: 6475

temp_dict = dict()
with open("test.dat", 'r') as f:
    lines = f.readlines()
    for i in range(0, len(lines), 2):
        keys = lines[i].split()
        vals = lines[i + 1].split()
        temp_dict.update(key: val for key, val in zip(keys, vals))

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

With str.split() and zip functions:

with open('test.dat', 'r') as f:
    d = {}
    for i,l in enumerate(f.read().splitlines()):
        if not i % 2:
            keys = l.split()
        else:
            d.update(zip(keys, l.split()))

print(d)

The output:

{'x1': '0.1', 'y1': '2', 'tf2': '8.9', 'ft': '4', 'x3': '0.8', 'gh3': '0.9', 'hh': '8', 'x2': '0.7', 'gt': '7'}

Upvotes: 0

Related Questions