我想使用Python将文件数据转换为3D字典。

huangapple go评论64阅读模式
英文:

I want to convert file data into 3d dictionary using python

问题

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'}
]

array=[]
with open("file.txt") as f:
    for line in f:
        array = line.split()
        break

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)
英文:

Like I want this type of dictionary by reading file:

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

or this will be enough.

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

I have a file lets name file.txt which has data like

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

I am trying but i dint get the result this following is my try:
it gives me output {'A': '7', 'B': '8', 'C': '9'}
I know its obvious it will not give me 3d dict but I don't know how to get there.

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)

答案1

得分: 3

你可以使用 Pandas

# Python环境:pip install pandas
# Anaconda环境:conda install pandas
import pandas as pd

df = pd.read_table('file.txt', sep=' ')
table = df.to_dict('index')
print(table)

# 输出
{0: {'A': 1, 'B': 2, 'C': 3},
 1: {'A': 4, 'B': 5, 'C': 6},
 2: {'A': 7, 'B': 8, 'C': 9}}
英文:

You can use 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}}

答案2

得分: 2

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

import csv

with open("data.csv", "r") as f_in:
    reader = csv.DictReader(f_in, delimiter=" ")
    # 如果文件包含浮点数,请使用 float(v) 而不是 int(v)
    # 如果您只想要字符串值,可以这样做:
    # 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}]
英文:

If you want to use just built-in modules, you can use 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)

Prints:

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

答案3

得分: 1

请使用以下代码:

table = {}

with open("file.txt") as f:
    headers = next(f).split()  # 从第一行获取表头
    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()  # 从第一行获取表头
    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'}
]
英文:

Try to use the following code:

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)

You should get format like this:

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

If you only want the inner dictionaries and not the outer structure, you can use a list instead of a dictionary to store the rows:

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)

This will give you the following output:

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

答案4

得分: 1

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'}]
英文:

DictReader from the csv module will give you what you seem to need - i.e., a list of dictionaries.

import csv

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

Output:

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

Optionally:

If you have an aversion to module imports you could achieve the same objective as follows:

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)

Output:

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

huangapple
  • 本文由 发表于 2023年1月9日 04:09:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75050924.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定