开发者

Python: Looping over One Dictionary and Creating Key/Value Pairs in a New Dictionary if Conditions Are Met

开发者 https://www.devze.com 2023-01-05 23:09 出处:网络
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 pairs that will vary de

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 pairs that will vary depending on the matches.

Here is a contrived example that shows my problem.

edit: sorry about all the returns, but stack overflow is not recognizing single returns and is running 3-4 lines onto one line, making the code illegible. also, it's not greying out my code as code. don't know why.

employee = {'skills': 'superintendent', 'teaches': 'social studies', 
            'grades': 'K-12'}
school_districts = {0: {'needs':  'superintendent', 'grades': 'K-12'}, 
                    1:{'needs': 'social_studies', 'grades': 'K-12'}}
jobs_in_school_district = {}
for key in school_districts:
    if (employee['skills'] == school_districts[key]['needs']):
        jobs_in_school_district[key] = {}
        jobs_in_school_district[key]['best_paying_job'] = 'superintendent'

    if (employee['teaches'] == school_districts[key]['needs']):
        jobs_in_school_district[key] = {}
        jobs_in_school_district[key]['other_job'] = 'social_studies_teacher'

print(jobs_in_school_district)

This is the value I want to see for 'jobs_in_school_district ':

{0: {'best_paying_job': 'superintendent'}, 
 1: {'other_job': 'social_studies_teacher'}}

This is what I'm getting:

{1: {'other_job': 'social_studies_teacher'}}

I understand what's wrong here. Python is setting jobs_in_school_district equal to {0: {'best_paying_job': 'superintendent'} after开发者_开发知识库 the first if block (lines 6-8). Then it executes the second if block (line 10). But then it overwrites the {0: {'best_paying_job': 'superintendent'} at line 11 and creates an empty dict again. Then it assigns 1: {'other_job': 'social_studies_teacher'}' to jobs_in_school_district at line 12.

But if I eliminate the two jobs_in_school_district[key] = {} in each of the for blocks (lines 7 and 11) and just put one before the 'for' statement (new line 5) like this:

jobs_in_school_district[key] = {}

for key in school_districts:
    if (employee['skills'] == school_districts[key]['needs']):
        jobs_in_school_district[key]['best_paying_job'] = 'superintendent'

    if (employee['teaches'] == jobs[key]['needs']):
        jobs_in_school_district[key]['other_job'] = 'social_studies_teacher'

print(jobs_in_school_district)

It will only check the first key in the 'school_districts' dict and then stop (it stops looping I guess, I don't know), so I get this:

jobs_in_school_district = {0: {'best_paying_job': 'superintendent'}

(I've tried re-writing it a few times and sometimes I get a "key error" instead).

First question: why doesn't that second block of code work? Second question: how do I write code so it does work?

(I don't really understand 'next' (method or function) and what it does, so if I have to use it, could you please explain? Thanks).


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:

import collections
jobs_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.


Try placing

jobs_in_school_district[key] = {}

after the for loop but before the if statements.

And yea the formatting is unreadable.


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'}}
0

精彩评论

暂无评论...
验证码 换一张
取 消