Doubt in code: Practice problem(Dictionaries)

Screen Link:

My Code:

from csv import reader
opene = open('sales.csv')
readd = reader(opene)
listy = list(readd)

sales =  {}
for item in listy[1:]:    
    if item not in sales:
        sales[item] += 1
        sales[item] = 1

What I expected to happen: I have written the following code so as to create a dictionary holding frequencies of the items of the list. However, my code isn’t working as I havent specified the index of the item column as a variable. Why is that necessary as there is only one column in the list.


Yes, you have to use the index because every element of the item column are store as a list. So, to get the value, we need to select the first element of the list i.e., index 0.

# listy is something like this
[['item'], ['Classic BAO'], ['Miso pork BAO'], ['Classic BAO'], ['Miso pork BAO']]

So, when you loop over it, then the type of item variable in the loop is a list or list cannot be used as a key in the dictionary. To select an element from the list, you need to specify its position.

I hope this will give you the answer.