Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a text file into a dictionary list

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!

like image 800
backofsky Avatar asked Nov 28 '25 18:11

backofsky


2 Answers

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())
like image 81
MoRe Avatar answered Nov 30 '25 08:11

MoRe


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}
]
like image 44
I'mahdi Avatar answered Nov 30 '25 08:11

I'mahdi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!