Python:如果条件满足,循环一个词典并在新词典中创建键/值对 [英] Python: Looping over One Dictionary and Creating Key/Value Pairs in a New Dictionary if Conditions Are Met

查看:125
本文介绍了Python:如果条件满足,循环一个词典并在新词典中创建键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个字典的值与第二个字典的值进行比较。如果值符合某些标准,我想创建一个具有键和值对的第三个字典,这些字符将根据匹配而有所不同。

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.

编辑:遗憾的是所有的回报,但堆栈溢出不识别单个回报,并在一行上运行3-4行,使代码难以辨认。同样,它不会将我的代码灰色化为代码。不知道为什么。

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)

这是我想要看到的值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'}}

这是我得到的:

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

我明白这里有什么问题Python在第一个if块之后设置 jobs_in_school_district 等于 {0:{'best_paying_job':'superintendent'} 线6-8)。然后它执行第二个if(块10)。但是它会覆盖第11行的 {0:{'best_paying_job':'superintendent'} ,并再次创建一个空的dict。然后在第12行将1:{'other_job':'social_studies_teacher'}'分配给 jobs_in_school_district

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.

但是如果我消除了每个块(第7行和第11行)中的两个 jobs_in_school_district [key] = {} ,并将其放在for语句之前(新行5)像这样:

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)

它只会检查'school_districts'dict中的第一个键,然后停止(它停止循环我猜,我不知道),所以我得到这个:

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).

推荐答案

最简单的修复(并回答你的第一个问题): key 在最新的片段中没有正确定义,分配必须是 c $ c> 如果 s:

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 ...

最简单的可能是使用默认的dict而不是普通的:

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

import collections
jobs_in_school_district = collections.defaultdict(dict)

现在您可以将作业删除到 [key] 索引,它将为您自动完成,如果和需要,第一次为任何给定键。

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.

这篇关于Python:如果条件满足,循环一个词典并在新词典中创建键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆