Gamer
Gamer

Reputation: 45

How to read data from a file into a dictionary?

I am trying to read information from a.txt file where each label is a dictionary key and each associated column of readings is the respective value.

Here's some lines in the file:

increments ideal actual measured
0.0, 1000.0, 1000.0, 1006.4882
1.0, 950.0, 973.2774, 994.5579
2.0, 902.5, 897.6053, 998.9594
3.0, 857.375, 863.4304, 847.4721
4.0, 814.5062, 813.8886, 866.4862
with open(filename, 'r') as file:
    labels = file.readline().rstrip('\n').split('\t')
    num_cols = len(labels)
    data = [[] for _ in range(num_cols)] 
    data_dict = {}

The above code is correct I just need to add on a little bit. How do I get the labels as dictionary keys and the columns as its values into data_dict?

Upvotes: 1

Views: 153

Answers (2)

sudheesh shivan
sudheesh shivan

Reputation: 41

You can use pandas to solve this

import pandas as pd

data_dict  = pd.read_csv('a.txt', sep=' ').to_dict(orient="index").values()

Upvotes: 1

Here's your solution:

with open("test.csv", 'r') as file:
    
    labels = file.readline().rstrip('\n').split() # read first line for labels
    data_dict = {l:[] for l in labels} # init empty container for each label

    for line in file.readlines(): # loop through rest of lines
        data = line.rstrip('\n').split(',')
        for n, datapoint in enumerate(data):
            data_dict[labels[n]].append(datapoint)

print(data_dict)
# >>> {'increments': ['0.0', '1.0', '2.0', '3.0', '4.0'], 'ideal': [' 1000.0', ' 950.0', ' 902.5', ' 857.375', ' 814.5062'], 'actual': [' 1000.0', ' 973.2774', ' 897.6053', ' 863.4304', ' 813.8886'], 'measured': [' 1006.4882', ' 994.5579', ' 998.9594', ' 847.4721', ' 866.4862']}

I was a bit confused about your input file. Your data seems to be comma separated but your headers are space separated? The concept here is basically that you create the dict with empty lists and then you can use the enumerate function and append the datapoint to the appropriate header. Hope this helps!

Upvotes: 1

Related Questions