Home > other >  Convert a text file into a dictionary list
Convert a text file into a dictionary list

Time:07-18

I have a text file in this format (in_file.txt):

banana 4500 9 
banana 350 0 
banana 550 8 
orange 13000 6

enter image description here

How can I convert this into a dictionary list in Python?

Code:

in_filepath = 'in_file.txt'

def data_dict(in_filepath):
    with open(in_filepath, 'r') as file:
        for line in file.readlines():
            title, price, count = line.split()

    d = {}
    d['title'] = title
    d['price'] = int(price)
    d['count'] = int(count)

    return [d]

The terminal shows the following result:

{'title': 'orange', 'price': 13000, 'count': 6}

Correct output:

{'title': 'banana', 'price': 4500, 'count': 9}, {'title': 'banana', 'price': 350, 'count': 0} , ....

Can anyone help me with my problem? Thank you!

CodePudding user response:

titles = ["title","price","count"]
[dict(zip(titles, [int(word) if word.isdigit() else word for word in line.strip().split()])) for line in open("in_file.txt").readlines()]

or:

titles = ["title","price","count"]
[dict(zip(titles, [(data:=line.strip().split())[0], *map(int, data[1:])])) for line in open("in_file.txt").readlines()]

your approach(corrected):

in_filepath = 'in_file.txt'

def data_dict(in_filepath):
    res = []
    with open(in_filepath, 'r') as file:
        for line in file.readlines():
            title, price, count = line.split()

            d = {}
            d['title'] = title
            d['price'] = int(price)
            d['count'] = int(count)
            res.append(d)
        
    return res

data_dict(in_filepath)

why? because

  1. ->
    d = {}
    d['title'] = title
    d['price'] = int(price)
    d['count'] = int(count)

is out of for loop and run only once and when ‍‍for be finished and then you have just one element

  1. you return your last element and didn't use others and use must create a list and append every element at the last line of for loop (saving) and at last, return result

@Rockbar approach:

import pandas as pd

list(pd.read_csv("in_file.txt", sep=" ", header=None, names=["title","price","count"]).T.to_dict().values())

CodePudding user response:

You can read the file line-by-line and then create dict base keys that define in the first.

keys = ['title', 'price' , 'count']
res = []
with open('in_file.txt', 'r') as file:
    for line in file:

     # Or in python >= 3.8
     # while (line := file.readline().rstrip()):

        tmp = [int(w) if w.isdigit() else w for w in line.rstrip().split() ]
        res.append(dict(zip(keys, tmp)))
print(res)

[
    {'title': 'banana', 'price': 4500, 'count': 9}, 
    {'title': 'banana', 'price': 350, 'count': 0}, 
    {'title': 'banana', 'price': 550, 'count': 8}, 
    {'title': 'orange', 'price': 13000, 'count': 6}
]

CodePudding user response:

You are trying to create list of dictionary (array of objects). So you should append dictionary into a list each time you created it from line of text.

Code

in_filepath = 'in_file.txt'


def data_dict(in_filepath):
    d = []
    with open(in_filepath, 'r') as file:
        for line in file.readlines():
            title, price, count = line.split()

            d.append({'title': title, 'price': int(price), 'count': int(count)})

    return d

Output

[
    {'title': 'banana', 'price': 4500, 'count': 9},
    {'title': 'banana', 'price': 350, 'count': 0},
    {'title': 'banana', 'price': 550, 'count': 8},
    {'title': 'orange', 'price': 13000, 'count': 6}
]
  • Related