Skip to content Skip to sidebar Skip to footer

Python: Looping Over One Dictionary And Creating Key/value Pairs In A New Dictionary If Conditions Are Met

I want to compare the values of one dictionary to the values of a second dictionary. If the values meet certain criteria, I want to create a third dictionary with keys and value p

Solution 1:

Simplest fix (and answer to your first question): key is not properly defined in your latest snippets, the assignment must be inside the for though outside the ifs:

for key in school_districts:
    jobs_in_school_district[key] = {}
    if ... etc etc ...
    if ... other etc etc ...

Simplest may actually be to use "default dicts" instead of plain ones:

importcollectionsjobs_in_school_district= collections.defaultdict(dict)

Now you can remove the assignment to the [key] indexing and it will be done for you, automatically, if and when needed for the first time for any given key.

Solution 2:

Try placing

jobs_in_school_district[key] = {}

after the for loop but before the if statements.

And yea the formatting is unreadable.

Solution 3:

If you change social_studies to social studies without the underscore the code works as you expected. See this line:

school_districts = {0: {'needs':  'superintendent', 'grades': 'K-12'}, 
                    1:{'needs': 'social_studies', 'grades': 'K-12'}}

Post a Comment for "Python: Looping Over One Dictionary And Creating Key/value Pairs In A New Dictionary If Conditions Are Met"