我想使用python将文件数据转换为3d字典



就像我想通过读取文件来获取这种类型的字典:

table = {
0: {'A': '1',   'B': '2',   'C': '3'},
1: {'A': '4',   'B': '5',   'C': '6'},
2: {'A': '7',   'B': '8',   'C': '9'}
}

或这将是足够的。

table = {
{'A': '1',   'B': '2',   'C': '3'},
{'A': '4',   'B': '5',   'C': '6'},
{'A': '7',   'B': '8',   'C': '9'}
}

我有一个文件名为file。txt的文件里面有类似

的数据
A B C
1 2 3
4 5 6
7 8 9

我正在尝试,但我没有得到的结果,这是我的尝试:它给了我输出{'A': '7', 'B': '8', 'C': '9'}我知道很明显它不会给我3d字典,但我不知道如何到达那里。

array=[]
with open("file.txt") as f:
for line in f:
array = line.split()
break #it will give me array=['A','B','C']

v=[]
dic = {}
for i in range(0,len(array)):
for line in open("file.txt"):
x=0
v = line.split() 
dic[ array[i] ] = v[i]    
print(dic)

您可以使用Pandas

# Python env: pip install pandas
# Anaconda env: conda install pandas
import pandas as pd
df = pd.read_table('file.txt', sep=' ')
table = df.to_dict('index')
print(table)
# Output
{0: {'A': 1, 'B': 2, 'C': 3},
1: {'A': 4, 'B': 5, 'C': 6},
2: {'A': 7, 'B': 8, 'C': 9}}

如果您只想使用内置模块,您可以使用csv.DictReader:

import csv
with open("data.csv", "r") as f_in:
reader = csv.DictReader(f_in, delimiter=" ")
# if the file countains floats use float(v) instead int(v)
# if you want values just strings you can do:
# data = list(reader)
data = [{k: int(v) for k, v in row.items()} for row in reader]

print(data)

打印:

[{"A": 1, "B": 2, "C": 3}, {"A": 4, "B": 5, "C": 6}, {"A": 7, "B": 8, "C": 9}]

尝试使用以下代码:

table = {}
with open("file.txt") as f:
headers = next(f).split()  # get the headers from the first line
for i, line in enumerate(f):
row = {}
for j, value in enumerate(line.split()):
row[headers[j]] = value
table[i] = row
print(table)

你应该得到这样的格式:

{
0: {'A': '1', 'B': '2', 'C': '3'},
1: {'A': '4', 'B': '5', 'C': '6'},
2: {'A': '7', 'B': '8', 'C': '9'}
}

如果您只需要内部字典而不需要外部结构,您可以使用列表而不是字典来存储行:

table = []
with open("file.txt") as f:
headers = next(f).split()  # get the headers from the first line
for line in f:
row = {}
for j, value in enumerate(line.split()):
row[headers[j]] = value
table.append(row)
print(table)

这将给你以下输出:

[
{'A': '1', 'B': '2', 'C': '3'},
{'A': '4', 'B': '5', 'C': '6'},
{'A': '7', 'B': '8', 'C': '9'}
]

来自csv模块的DictReader将为您提供您似乎需要的东西-即字典列表。

import csv
with open('file.txt', newline='') as data:
result = list(csv.DictReader(data, delimiter=' '))
print(result)

输出:

[{'A': '1', 'B': '2', 'C': '3'}, {'A': '4', 'B': '5', 'C': '6'}, {'A': '7', 'B': '8', 'C': '9'}]

(可选):

如果您不喜欢导入模块,您可以实现以下相同的目标:

result = []
with open('file.txt') as data:
columns = data.readline().strip().split()
for line in map(str.strip, data):
result.append(dict(zip(columns, line.split())))
print(result)

输出:

[{'A': '1', 'B': '2', 'C': '3'}, {'A': '4', 'B': '5', 'C': '6'}, {'A': '7', 'B': '8', 'C': '9'}]

相关内容

  • 没有找到相关文章

最新更新