简体   繁体   English

如何从文件中读取数据到字典中?

[英]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.我正在尝试从 a.txt 文件中读取信息,其中每个 label 都是字典键,每个关联的读数列都是各自的值。

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?如何将标签作为字典键并将列作为其值获取到 data_dict 中?

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!这里的概念基本上是你用空列表创建字典,然后你可以使用enumerate function 和 append 数据点到适当的 header。希望这有帮助!

You can use pandas to solve this您可以使用 pandas 来解决这个问题

import pandas as pd

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM