Different results by 1

My Code:

decade_frequency = {}
for decade in decades:
    if decade not in decade_frequency:
        decade_frequency[decade] = 1
    if decade in decade_frequency:
        decade_frequency[decade] += 1
        
print(decade_frequency) 

Result:

{'30s': 4723, '60s': 1358, '70s': 560, '40s': 4082, '50s': 2435, '20s': 1857, 'Unknown': 1094, '90s': 254, '80s': 365, '100s': 4, '110s': 4}

Correct Answer:

decade_frequency1 = {}
for d in decades:
    if d not in decade_frequency1:
        decade_frequency1[d] = 1
    else:
        decade_frequency1[d] += 1
print(decade_frequency1)

Result:

{'30s': 4722, '60s': 1357, '70s': 559, '40s': 4081, '50s': 2434, '20s': 1856, 'Unknown': 1093, '90s': 253, '80s': 364, '100s': 3, '110s': 3}

Dear Community,
I have no idea why the codes make difference. The only difference is “if… in” in my code & “else” in the correct answer, but not sure why it would make different results. Why does the correct one have one less in each values?

Let’s say your for loop has been running for a while. And right now, your decade_frequency dictionary contains -

decade_frequency = {"30s": 4, "40s": 5}

Now, consider the next iteration of your loop where decade is "30s".

For first part of your loop -

if decade not in decade_frequency:
        decade_frequency[decade] = 1

After the above code runs, what would decade_frequency contain?

Now, let’s go to the second part of your loop -

if decade in decade_frequency:
        decade_frequency[decade] += 1

After the above code runs, what would decade_frequency contain?

Now, move forward by one iteration. This time, decade is "50s".

Repeat the process above for both the parts I mentioned with this value for decade. After both of those parts, what would decade_frequency contain? Write it down and see whether or not that looks correct to you.

If you get stuck or confused, feel free to ask more questions.

ahhhh i got it, after operating

if decade not in decade_frequency:
        decade_frequency[decade] = 1

the decade that was not in the decade_frequency will be added to the library, so then it’ll make

if decade in decade_frequency 

true, so it’ll add one more. Thank you so much! well-understood :slight_smile:

1 Like