[英]Python: Looping over One Dictionary and Creating Key/Value Pairs in a New Dictionary if Conditions Are Met
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. 这是一个显示我的问题的人为例子。
edit: sorry about all the returns, but stack overflow is not recognizing single returns and is running 3-4 lines onto one line, making the code illegible. 编辑:抱歉所有的返回,但堆栈溢出不识别单个返回,并在一行上运行3-4行,使代码难以辨认。 also, it's not greying out my code as code.
另外,它并没有使我的代码变灰为代码。 don't know why.
不知道为什么。
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)
This is the value I want to see for 'jobs_in_school_district ': 这是我想要查看'jobs_in_school_district'的值:
{0: {'best_paying_job': 'superintendent'},
1: {'other_job': 'social_studies_teacher'}}
This is what I'm getting: 这就是我得到的:
{1: {'other_job': 'social_studies_teacher'}}
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). Python在第一个if块(第6-8行)之后将
jobs_in_school_district
设置jobs_in_school_district
等于{0: {'best_paying_job': 'superintendent'}
。 Then it executes the second if block (line 10). 然后它执行第二个if块(第10行)。 But then it overwrites the
{0: {'best_paying_job': 'superintendent'}
at line 11 and creates an empty dict again. 但是它会在第11行覆盖
{0: {'best_paying_job': 'superintendent'}
并再次创建一个空的dict。 Then it assigns 1: {'other_job': 'social_studies_teacher'}' to jobs_in_school_district
at line 12. 然后它在第12行向
jobs_in_school_district
分配1:{'other_job':'social_studies_teacher'}'。
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: 但是如果我在每个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)
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: 它只会检查'school_districts'字典中的第一个键然后停止(它会停止循环我猜,我不知道),所以我得到了这个:
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). (我真的不明白'下一个'(方法或功能)及其作用,所以如果我必须使用它,你能解释一下吗?谢谢)。
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 if
s: 最简单的修复(并回答您的第一个问题):
key
未在您的最新代码段中正确定义,分配必须在 for
内部 for
但在if
s之外:
for key in school_districts:
jobs_in_school_district[key] = {}
if ... etc etc ...
if ... other etc etc ...
Simplest may actually be to use "default dicts" instead of plain ones: 最简单的可能是使用“默认dicts”而不是普通的dicts:
import collections
jobs_in_school_district = collections.defaultdict(dict)
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. 现在,您可以删除
[key]
索引的分配,并且将在第一次为任何给定密钥需要时自动为您完成。
Try placing 尝试放置
jobs_in_school_district[key] = {}
after the for loop but before the if statements. 在for循环之后但在if语句之前。
And yea the formatting is unreadable. 格式化是不可读的。
If you change social_studies to social studies without the underscore the code works as you expected. 如果您将social_studies更改为没有下划线的社会研究,则代码可以按预期运行。 See this line:
看到这一行:
school_districts = {0: {'needs': 'superintendent', 'grades': 'K-12'},
1:{'needs': 'social_studies', 'grades': 'K-12'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.