Skip to content
Advertisement

Why is my attempt to iterate through a list of lists and update dictionary values resulting in unchanged dictionary?

I want to iterate through a list of lists and if an instance in the list matches a key in a dictionary, add 1 to that dictionary key value. However, when I execute my code it returns the dictionary with no changes to the values. Thank you for your time & help. I searched for a similar question but did not find one that addressed this issue. My apologies if I missed it.

I have a list of hurricanes and the areas they affected. I have a dictionary with key, value pairs for the uniquely affected area, and the number of times affected (set to zero). I want to iterate through the list of hurricane instances and each time I pass through a location in the dictionary increase the value of the unique area by 1. Currently, with the code I’m running the returned dictionary is unchanged.

I’ve included smaller examples of material I’m working with: (test_list is a list of areas affected by a hurricane resulting in a list of lists)

JavaScript

GOAL

if I performed:

JavaScript

I would have expected:

JavaScript

However, this was not my result.

CODE

JavaScript

outputs the following:

JavaScript

edit-1: edited area_count parameters to input_list instead of list, corrected parameter input order for area_counted to match area_count function.

Advertisement

Answer

new_dict[j] always is equal to 0 initially (since in test_dict all the values are 0)

you are comparing it to a string

JavaScript

hopefully you can see how this never sets it to 1

I think what you want is

JavaScript

as an unrelated aside you really should not name a variable list as that is a built in entity that you end up shadowing

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement