0

I need to convert a csv file into a dictionary.The input file is 4 columns and about food from Chick Fila.

I want the dictionary to return something like this:

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

it is the item, price, calories, and type

I have tried so many times to figure it out. I am in an intro to python class. So far I have this code:

 def read_file(filename):

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

        for line in f: 

Any help would be amazing!

greg-449
  • 109,219
  • 232
  • 102
  • 145
  • I am super new to python. How would I use that –  Apr 09 '20 at 22:24
  • it is 4 columns. First column is item, then price, calories, and Type. –  Apr 09 '20 at 22:30
  • The Key is the Item and the value needs to be a tuple that contains the price (float), calories(int), type(str)). –  Apr 09 '20 at 22:31
  • Please don't vandalize your own posts. When you post here, you give SO the right to distribute the content under CC-by SA 4.0. Any vandalism will be reverted. – greg-449 Apr 11 '20 at 15:56
  • okay i see, gotcha –  Apr 11 '20 at 15:57

1 Answers1

1

You can do this nicely using Pandas.

considering CSV file like:

╔══════════════════════════╦══════╦═════╦═════════╗
║           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')

This gives you something that looks like {index -> {column -> value}}, so to get it to the final form {index -> (values)} you can iterate:

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

output:

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

Mohsen
  • 1,079
  • 2
  • 8
  • 23
Philip Ciunkiewicz
  • 2,652
  • 3
  • 12
  • 24
  • pciunkiewicz,clear answer, just some more explanation added to make it more clear if you accept – Mohsen Apr 09 '20 at 23:02