【问题标题】:Converting a text file to a dictionary in Python [duplicate]在Python中将文本文件转换为字典[重复]
【发布时间】:2020-07-22 15:56:15
【问题描述】:

我需要将 csv 文件转换为字典。输入文件是 4 列,内容是关于 Chick Fila 的食物。

我希望字典返回如下内容:

{ “Spicy Chicken Sandwich” : (3.99,  460, 'Entrees'), “Grilled Chicken Sandwich” : (5.15, 320, 'Entrees'),  “Market Salad” : (8.19,  250,  'Salads') }.

它是商品、价格、卡路里和类型

我已经尝试了很多次才能弄清楚。我正在介绍 python 类。到目前为止,我有这个代码:

 def read_file(filename):

    with open("menu1.csv") as f:

        for line in f: 

任何帮助都会很棒!

【问题讨论】:

  • 我是 python 的超级新手。我将如何使用它
  • 它是 4 列。第一列是商品,然后是价格、卡路里和类型。
  • Key是Item,value需要是一个元组,包含价格(float)、calories(int)、type(str))。
  • 请不要破坏您自己的帖子。当您在此处发帖时,您授予 SO 根据 CC-by SA 4.0 分发内容的权利。任何破坏行为都将被撤销。
  • 好吧,我明白了

标签: python


【解决方案1】:

您可以使用 Pandas 很好地做到这一点。

考虑 CSV 文件,例如:

╔══════════════════════════╦══════╦═════╦═════════╗
║           Name           ║  H1  ║ H2  ║   H3    ║
╠══════════════════════════╬══════╬═════╬═════════╣
║ Spicy Chicken Sandwich   ║ 3.99 ║ 460 ║ Entrees ║
║ Grilled Chicken Sandwich ║ 5.15 ║ 320 ║ Entrees ║
║ Market Salad             ║ 8.19 ║ 250 ║ Salads  ║
╚══════════════════════════╩══════╩═════╩═════════╝
import pandas as pd

df = pd.read_csv("menu1.csv")

df = df.set_index(<column you want as keys>)

result = df.to_dict('index')

这给了你一些看起来像{index -&gt; {column -&gt; value}}的东西,所以为了得到最终形式{index -&gt; (values)},你可以迭代:

result = {key: tuple(val.values()) for key, val in result.items()}

输出:

{'Spicy Chicken Sandwich': (3.99, 460, 'Entrees'), 'Grilled Chicken Sandwich': (5.15, 320, 'Entrees'), 'Market Salad': (8.19, 250, 'Salads')}

【讨论】:

  • pciunkiewicz,明确的答案,只是添加了一些解释,以便您接受时更清楚
猜你喜欢
  • 2020-11-24
  • 2020-09-24
  • 2021-04-01
  • 2020-12-16
  • 2023-03-15
  • 2016-10-31
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多