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

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

enter image description here

如何将其转换为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} , ....

有人能帮我解决这个问题吗?非常感谢.

推荐答案

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)

for次循环中,仅在以下时间运行一次‍‍for完成后,你只有一个元素

  1. 您返回最后一个元素,但没有使用其他元素,并且使用必须创建一个列表,并将每个元素附加到for循环(保存)的最后一行,最后返回结果

@Rockbar进近:

import pandas as pd

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

Python相关问答推荐

Maya Python脚本将纹理应用于所有对象,而不是选定对象

在方法中设置属性值时,如何处理语句不可达[Unreacable]";的问题?

如何在海上配对图中使某些标记周围的黑色边框

pandas:在操作pandora之后将pandora列转换为int

Python 3试图访问在线程调用中实例化的类的对象

如何为需要初始化的具体类实现依赖反转和接口分离?

Pandas:计数器的滚动和,复位

PYTHON中的selenium不会打开 chromium URL

对于数组中的所有元素,Pandas SELECT行都具有值

按列表分组到新列中

当lambda函数作为参数传递时,pyo3执行

如何在函数签名中输入数据类字段

如何从多个词典中制作Pandas 数据帧?

属性错误:';Styler';对象没有属性';样式';

是否可以在dash-cytoscape中使用宽度优先布局中的epthSort参数?

从html获取元素时出现问题

巨 Python 品脱摄氏度单位

将函数拟合到曲线上,然后删除某些点

加快滚动总和计算速度?

Pandas Groupby在try 聚合列时引发ValueError:LEN(索引)!=len(标签)