So I've looked all over the place and cant seem to get an answer that I understand. I am trying to implement a piece of code where Python looks at a text file, gets a line, and looks for a dictionary with a corresponding name. Here is my code so far:
f = open("data.txt", "r")
content = f.readlines()
icecream = {
"fat": 80,
"carbohydrates": 50,
"protein": 650,
"calories": 45,
"cholesterol": 50,
"sodium": 50,
"name": "Icecream"
}
bigmac = {
"fat": 29,
"carbohydrates": 45,
"protein": 25,
"sodium": 1040,
"cholesterol": 75,
"calories": 540,
"name": "Big Mac"
}
whopper = {
"fat": 47,
"carbohydrates": 53,
"protein": 33,
"sodium": 1410,
"cholesterol": 100,
"calories": 760,
"name": "Whopper"
}
menu = [
bigmac,
whopper,
icecream
]
sea = content[0]
for line in enumerate(menu):
if sea.lower() in line['name'].lower():
print (line['name'])
I keep getting the error TypeError: tuple indices must be integers or slices, not str and I don't understand why. Could someone help me fix my code and possibly get my 2 brain-cells to understand why this error comes up?
CodePudding user response:
Update your code to :
for line in menu:
if sea.lower() in line['name'].lower():
print (line['name'])
"enumerate" is useless with menu that is already an array
CodePudding user response:
Your error arises when calling line['name']
, as line
is a tuple produced by the enumerate
call:
(0, {'fat': 29, 'carbohydrates': 45, 'protein': 25, 'sodium': 1040, 'cholesterol': 75, 'calories': 540, 'name': 'Big Mac'})
(1, {'fat': 47, 'carbohydrates': 53, 'protein': 33, 'sodium': 1410, 'cholesterol': 100, 'calories': 760, 'name': 'Whopper'})
(2, {'fat': 80, 'carbohydrates': 50, 'protein': 650, 'calories': 45, 'cholesterol': 50, 'sodium': 50, 'name': 'Icecream'})
As such, it will need a integer in order to know which of menu
's items to call.
CodePudding user response:
enumerate()
returns a tuple of index and element. E.g.:
>>> for item in enumerate(["a", "b", "c"]):
>>> print(item)
(0, "a")
(0, "b")
(0, "c")
So when you enumerate over your menu
list, your item is not this dict, but tuple of index and dict. If you don't need index of element, use:
for line in menu:
if sea.lower() in line['name'].lower():
print (line['name'])
If you need index, use:
for i, line in enumerate(menu):
if sea.lower() in line['name'].lower():
print (i, line['name'])
CodePudding user response:
enumerate(menu) returns a "tuple" and the way you were accessing it as a dictionary has caused this error. Also, use splitlines to handle if there is any new-line characters in the read string.
So, change the code as below without enumerate.
sea = content.splitlines()[0]
for line in menu:
if sea.lower() in line['name'].lower():
print (line['name'])
This depends on how the input file data is. Share us how the input file looks like, if this is not working.