Python:在一个字典上循环,如果条件是M,则在新字典中创建键/值对

2024-05-15 11:10:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想比较一本字典和另一本字典的值。如果值满足某些条件,我想创建第三个字典,其中的键和值对将根据匹配情况而变化。在

这是一个人为的例子,说明了我的问题。在

编辑:对于所有的返回,很抱歉,但是堆栈溢出无法识别单个返回,并且在一行上运行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)

这是我希望看到的“就业机会”在“学区”的价值:

^{pr2}$

我得到的是:

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

我明白这是怎么回事。Python在第一个if块(第6-8行)之后将jobs_in_school_district设置为{0: {'best_paying_job': 'superintendent'}。然后执行第二个if块(第10行)。但随后它重写了第11行的{0: {'best_paying_job': 'superintendent'},并再次创建一个空dict。然后在第12行将1:{'other\'job':'social_studies_teacher'}'分配给jobs_in_school_district。在

但是如果我消除了for块(第7行和第11行)中的两个jobs_in_school_district[key] = {},只在“for”语句(新的第5行)前面放一个,如下所示:

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)

它只会检查“学区”dict中的第一个键,然后停止(它停止循环,我想,我不知道),所以我得到:

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

(我试着重新写了几次,但有时会出现“键错误”)。在

第一个问题:为什么第二块代码不起作用? 第二个问题:我如何编写代码使其正常工作?在

(我不太了解“下一步”(方法或函数)以及它的作用,所以如果我必须使用它,请您解释一下好吗?谢谢)。在


Tags: keyinifjobsemployeejobsocialbest
3条回答

尝试放置

jobs_in_school_district[key] = {}

在for循环之后但在if语句之前。在

而且格式是不可读的。在

如果您将社会研究更改为不带下划线的社会研究,则代码将按预期工作。请看这一行:

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

最简单的修复方法(以及对第一个问题的回答):key在最新的代码片段中没有正确定义,赋值必须在{}之外的{}内:

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

    if ... other etc etc ...

实际上,最简单的方法可能是使用“默认dict”而不是普通dict:

^{pr2}$

现在,您可以删除对[key]索引的赋值,并且当第一次需要任何给定的键时,它将自动为您完成。在

相关问题 更多 >