Skip to content
Advertisement

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

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)

Advertisement

Answer

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'}
]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement