Hi I have a question about iterating through a list and adding items and their frequency within the list to a dictionary.
i = ['apple','pear','red','apple','red','red','pear','pear','pear']
d = {x:i.count(x) for x in i}
print (d)
outputs
{'pear': 4, 'apple': 2, 'red': 3}
However
i = ['apple','pear','red','apple','red','red','pear', 'pear', 'pear']
d = {}
for x in i:
d={x:i.count(x)}
print(d)
outputs
{'pear': 4}
I need to iterate through the list while adding each iteration within the dictionary to a new list. However I can't understand why the two different codes are giving different results.
It's encouraging to seee that the count function works on the second one. But I am confused as to where apple and red dissapeared to.
Sorry for bad wording etcetera been working on this hours and is driving me crazy. Thanks so much for taking time to help
I am confused as to why the two results are different