Unexpected Value Overwriting in Python Dictionary During Loop - How to Preserve Original Values?
I've been banging my head against this for hours. I'm stuck on something that should probably be simple..... I'm sure I'm missing something obvious here, but I'm working on a script in Python 3.11 where I'm trying to aggregate some data into a dictionary. Specifically, I'm trying to create a frequency count of items in a list of tuples. However, I'm working with an scenario where the values in my dictionary appear to be overwriting each other during the loop. Here's the part of the code where I'm working with the question: ```python items = [('apple', 1), ('banana', 2), ('apple', 3), ('orange', 1)] frequency = {} for item, count in items: if item in frequency: frequency[item] += count # This line seems to cause issues else: frequency[item] = count ``` After running this, I expect the `frequency` dictionary to contain `{'apple': 4, 'banana': 2, 'orange': 1}`. However, the output I get is `{'apple': 3, 'banana': 2, 'orange': 1}`. It seems that the count for 'apple' is not being incremented correctly. I double-checked the values in the list of tuples, and they seem correct. I also tried printing the intermediate values inside the loop but it only shows correct counts being processed each time. I need to figure out why the final count for 'apple' seems to be off. Any advice on how to preserve the original values when updating or should I change my approach to aggregating these counts? This is part of a larger API I'm building. What am I doing wrong? My development environment is Windows. What am I doing wrong? Is this even possible?