Struggling to work out why it wont read my list as an integer? Could someone shed some light on what I seem to be missing? x
Here’s the challenge I was working on: Create a dictionary with 3 key:value pairs, called dict. Write a FOR Loop that loops for the length of dictionary.values(), and prints out each value.
Heres what I think I’ve done.
- Created my dictionary w/ keys & values.
- Converted my dictionary values into a list
- Created a for loop and asked it to print each iteration.
dict = {
'eggs' : 5,
'chips' : 4,
'ham' : 3
}
dictList = list(dict.values())
for i in range(dictList):
print(dictList[i])
**
Could someone explain the error to me too?**
TypeError: 'list' object cannot be interpreted as an integer
>Solution :
You don’t need to convert dict into a list, as you can just iterate over dict.values(). Since lists in Python are already iterable (that is, they can be looped over), you 1) don’t need to iterate over the range of the length of the list, and 2) don’t need to index into the list with dictList[i]
Instead, you can simply do the following:
dict = {
'eggs' : 5,
'chips' : 4,
'ham' : 3
}
for value in dict.values():
print(value)