Home > front end >  I need to read a file and turn it into a dictionary
I need to read a file and turn it into a dictionary

Time:11-27

I have a file of recipes

banana pancake
1 cups of flour
2 tablespoons of sugar
1 eggs
1 cups of milk
3 teaspoons of cinnamon
2 teaspoons of baking powder
0 slices of bread
2 bananas
0 apples
0 peaches

And I need to create a dictionary, where the key is the name of the ingredient and the value is the respective unit.

Example {
           'cups of flower': 1
           'tablespoons of sugar': 2
           ...
        } 

This is what I tried to do

file = open('recipe.txt', 'r')
alpha = 'abcdefghijklmnopqrstuvwxyz'
d = {}
for line in file:
  if line[0] in alpha:#this makes sure that the for loop "ignores" the first line for each recipe, which contains the name of the meal
    continue
  else:
    line1  = line.split(' ') #splits lines into lists 
    d[line1[1:]] = line1[0] #grabs keys and values 
    print(d)  

CodePudding user response:

Running your code generates an error that looks something like this:

TypeError                                 Traceback (most recent call last)
<ipython-input-14-08149fb7c88a> in <module>
      6   else:
      7     line1  = line.split(' ') #splits lines into lists
----> 8     d[line1[1:]] = line1[0] #grabs keys and values
      9     print(d)
     10

TypeError: unhashable type: 'list'

The error message indicates that you're trying to use a list (line1[1:]) as a dictionary key, which is not allowed. That's not really what you want either. Take the list of words and turn them back into a string and use that as your key instead.

key = ' '.join(line1[1:]) # join list elements together, separated by a space
d[key] = line1[0]

This question has more details about what you can and can't use as dict keys.

In the future be sure to include details like any error or traceback messages you get in your question. Welcome to SO!

CodePudding user response:

You don't need the alpha variable to ignore the first line you just pop the first element from the list of lines of the file. Code should be like this:

file = open("recipe.txt", "r")
dictionary = dict()
lines = file.readlines()
lines.pop(0)

for line in lines:
    line = line.split()
    ingredients = line[1:]
    ingredients = ' '.join(ingredients)
    dictionary[ingredients] = int(line[0])

print(dictionary)

Output Example of your file:

{'cups of flour': 1, 'tablespoons of sugar': 2, 'eggs': 1, 'cups of milk': 1, 'teaspoons of cinnamon': 3, 'teaspoons of baking powder': 2, 'slices of bread': 0, 'bananas': 2, 'apples': 0, 'peaches': 0}

  • Related