Convert a text file into a dictionary list

Question:

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!

Asked By: backofsky

||

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())
Answered By: MoRe

You are trying to create a list of dictionaries (array of objects). So it would be best if you appended dictionary into a list each time you created it from a line of text.

Code

in_filepath = 'in_file.txt'


def data_dict(in_filepath):
    dictionary = []
    with open(in_filepath, 'r') as file:
        for line in file:
            title, price, count = line.split()
            dictionary.append({'title': title, 'price': int(price), 'count': int(count)})

    return dictionary


print(data_dict(in_filepath))

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}
]
Answered By: bekirbakar

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}
]
Answered By: I'mahdi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.