我想将一个字典的值与第二个字典的值进行比较。如果值满足特定条件,我想创建第三个字典,其中的键和值对将根据匹配情况而变化。
这是一个显示我的问题的人为示例。
编辑:对所有返回感到抱歉,但堆栈溢出无法识别单个返回,并且在一行上运行 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 正在设置jobs_in_school_district
等于{0: {'best_paying_job': 'superintendent'}
在第一个 if 块之后(第 6-8 行)。然后它执行第二个 if 块(第 10 行)。但随后它会覆盖{0: {'best_paying_job': 'superintendent'}
在第 11 行并再次创建一个空字典。然后它将 1: {'other_job': 'social_studies_teacher'}' 分配给jobs_in_school_district
在第 12 行。
但如果我消除这两个jobs_in_school_district[key] = {}
在每个 for 块(第 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”(方法或函数)及其作用,所以如果我必须使用它,你能解释一下吗?谢谢)。