【发布时间】:2011-03-10 21:10:54
【问题描述】:
我想将一个字典的值与第二个字典的值进行比较。如果值符合某些条件,我想创建第三个字典,其中的键和值对会因匹配项而异。
这是一个人为的例子来说明我的问题。
编辑:对所有返回感到抱歉,但堆栈溢出无法识别单个返回,并且在一行中运行 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 块(第 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)
它只会检查“school_districts”字典中的第一个键,然后停止(我猜它会停止循环,我不知道),所以我明白了:
jobs_in_school_district = {0: {'best_paying_job': 'superintendent'}
(我已经尝试重写了几次,但有时我会得到一个“关键错误”)。
第一个问题:为什么第二个代码块不起作用? 第二个问题:我如何编写代码才能正常工作?
(我不太了解'next'(方法或函数)以及它的作用,所以如果我必须使用它,您能解释一下吗?谢谢)。
【问题讨论】:
-
你应该在这里阅读如何格式化代码示例,这是不可读的。
-
除非有办法强制,否则它拒绝这样做。
标签: python dictionary conditional key iteration