Jan-19-2020, 02:02 PM
Not sure that answers OPs question. That was to print the count of the most frequent item, not the frequency of the last item in the list. By that, you would need to sort the dictionary by value and then take the last dictionary item. If you add a 3 to the end of his list, the posted code yields 3 which is incorrect - the max is still 4, based on the most frequent item (2).
Add one step, sort by value, then print which item is most frequent and that item's frequency:
Add one step, sort by value, then print which item is most frequent and that item's frequency:
lst = [3,5,2,1,2,3,2,2,3] # list to be iterated counts = dict() # dictionary for keeping counts of occurances for item in lst: # iterate all list items try: # try +1 to value of key counts[item] += 1 except KeyError: # if key is not existing (raises KeyError) counts[item] = 1 # add key and set value to 1 (first count) counts = sorted(counts.items(), key = lambda kv:(kv[1], kv[0])) print(f'Most common is {counts[-1][0]} with a frequency of {counts[-1][1]}')