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

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

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

问题

  1. table = {
  2. 0: {'A': '1', 'B': '2', 'C': '3'},
  3. 1: {'A': '4', 'B': '5', 'C': '6'},
  4. 2: {'A': '7', 'B': '8', 'C': '9'}
  5. }
  6. table = [
  7. {'A': '1', 'B': '2', 'C': '3'},
  8. {'A': '4', 'B': '5', 'C': '6'},
  9. {'A': '7', 'B': '8', 'C': '9'}
  10. ]
  11. array=[]
  12. with open("file.txt") as f:
  13. for line in f:
  14. array = line.split()
  15. break
  16. v=[]
  17. dic = {}
  18. for i in range(0,len(array)):
  19. for line in open("file.txt"):
  20. x=0
  21. v = line.split()
  22. dic[ array[i] ] = v[i]
  23. print(dic)
英文:

Like I want this type of dictionary by reading file:

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

or this will be enough.

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

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

  1. A B C
  2. 1 2 3
  3. 4 5 6
  4. 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.

  1. array=[]
  2. with open("file.txt") as f:
  3. for line in f:
  4. array = line.split()
  5. break #it will give me array=['A','B','C']
  6. v=[]
  7. dic = {}
  8. for i in range(0,len(array)):
  9. for line in open("file.txt"):
  10. x=0
  11. v = line.split()
  12. dic[ array[i] ] = v[i]
  13. print(dic)

答案1

得分: 3

你可以使用 Pandas

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

You can use Pandas

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

答案2

得分: 2

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

  1. import csv
  2. with open("data.csv", "r") as f_in:
  3. reader = csv.DictReader(f_in, delimiter=" ")
  4. # 如果文件包含浮点数,请使用 float(v) 而不是 int(v)
  5. # 如果您只想要字符串值,可以这样做:
  6. # data = list(reader)
  7. data = [{k: int(v) for k, v in row.items()} for row in reader]
  8. print(data)

输出:

  1. [{"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:

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

Prints:

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

答案3

得分: 1

请使用以下代码:

  1. table = {}
  2. with open("file.txt") as f:
  3. headers = next(f).split() # 从第一行获取表头
  4. for i, line in enumerate(f):
  5. row = {}
  6. for j, value in enumerate(line.split()):
  7. row[headers[j]] = value
  8. table[i] = row
  9. print(table)

你应该得到如下格式的输出:

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

如果你只想要内部的字典而不包括外部的结构,你可以使用列表来存储行:

  1. table = []
  2. with open("file.txt") as f:
  3. headers = next(f).split() # 从第一行获取表头
  4. for line in f:
  5. row = {}
  6. for j, value in enumerate(line.split()):
  7. row[headers[j]] = value
  8. table.append(row)
  9. print(table)

这将给你以下输出:

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

Try to use the following code:

  1. table = {}
  2. with open("file.txt") as f:
  3. headers = next(f).split() # get the headers from the first line
  4. for i, line in enumerate(f):
  5. row = {}
  6. for j, value in enumerate(line.split()):
  7. row[headers[j]] = value
  8. table[i] = row
  9. print(table)

You should get format like this:

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

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:

  1. table = []
  2. with open("file.txt") as f:
  3. headers = next(f).split() # get the headers from the first line
  4. for line in f:
  5. row = {}
  6. for j, value in enumerate(line.split()):
  7. row[headers[j]] = value
  8. table.append(row)
  9. print(table)

This will give you the following output:

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

答案4

得分: 1

csv模块中的DictReader会提供你所需的内容,即一个字典列表。

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

输出:

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

可选:

如果你不喜欢导入模块,也可以通过以下方式实现相同的目标:

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

输出:

  1. [{'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.

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

Output:

  1. [{'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:

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

Output:

  1. [{'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:

确定