Python:遍历一个字典并在条件满足时创建新的键值对

4 投票
3 回答
2145 浏览
提问于 2025-04-16 00:42

我想把一个字典里的值和另一个字典里的值进行比较。如果这些值符合某些条件,我想创建一个第三个字典,里面的键和值会根据匹配的结果而变化。

下面是一个简单的例子,展示了我遇到的问题。

编辑:抱歉有这么多换行,但Stack Overflow没有识别单个换行,把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 ' 的值:

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

这是我得到的结果:

{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'},重新创建了一个空字典。然后在第12行把1: {'other_job': 'social_studies_teacher'}'赋值给jobs_in_school_district

但是如果我把每个for块里的两个jobs_in_school_district[key] = {}(第7和11行)去掉,只在'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)

它只会检查'school_districts'字典里的第一个键,然后就停止了(我想它停止循环了,我也不太清楚),所以我得到了这个结果:

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

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

第一个问题:为什么那第二段代码不工作?

第二个问题:我该怎么写代码才能让它工作?

(我不太理解'next'(方法或函数)是什么,也不知道它的作用,如果我必须用到它,能不能请你解释一下?谢谢)。

3 个回答

0

如果你把“social_studies”改成“social studies”,也就是去掉下划线,这段代码就能按你想要的那样运行了。看看这一行:

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

试着把

jobs_in_school_district[key] = {}

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

对了,格式确实看起来很乱。

3

最简单的解决办法(也是你第一个问题的答案):在你最新的代码片段中,key 没有正确定义,赋值操作必须放在 for 循环里面,但要在 if 语句外面:

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

    if ... other etc etc ...

其实最简单的方法可能是使用“默认字典”,而不是普通的字典:

import collections
jobs_in_school_district = collections.defaultdict(dict)

现在你可以去掉对 [key] 的赋值操作,如果某个键第一次需要用到,它会自动为你完成这个操作。

撰写回答