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

Time:01-09

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)

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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