python 将文本文件转换为词典列表

von4xj4u  于 2023-01-08  发布在  Python
关注(0)|答案(3)|浏览(187)

我有一个这种格式的文本文件(in_file. txt):

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

在Python中如何将其转换为字典列表?
代码:

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]

终端显示以下结果:

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

正确输出:

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

有人能帮我解决这个问题吗?谢谢!

wnrlj8wa

wnrlj8wa1#

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()]

或:

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

您的方法(更正):

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)

为什么?因为
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.返回最后一个元素,并且没有使用其他元素,使用必须创建一个列表,并将每个元素附加到for循环的最后一行(保存),最后返回结果
@岩杆方法:

import pandas as pd

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

e0uiprwp2#

您可以逐行读取文件,然后创建在第一个中定义的dict基键。

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

fd3cxomn3#

您正在尝试创建一个字典列表(对象数组),因此最好在每次从一行文本创建list时都将其追加到dictionary中。
代码

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

产出

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

相关问题