[英]Update list of dictionaries based on another list of dictionaries
I have two lists of dictionaries, one is a list of project identifiers and the other a list of completed project identifiers. 我有两个字典列表,一个是项目标识符列表,另一个是已完成项目标识符列表。 I'm looking to add a key to the project identifier list, based on existence in the completed list.
我正在根据完成列表中的存在情况,将密钥添加到项目标识符列表中。
Current code 当前代码
>>> projects = [{'id': 1}, {'id': 2}, {'id': 3}]
>>> completes = [{'id': 1}, {'id': 2}]
>>> for complete in completes:
... for project in projects:
... if project["id"] == complete["id"]:
... project["complete"] = 1
... else:
... project["complete"] = 0
...
>>> print projects
[{'id': 1, 'complete': 0}, {'id': 2, 'complete': 1}, {'id': 3, 'complete': 0}]
Expected output 预期产量
[{'id': 1, 'complete': 1}, {'id': 2, 'complete': 1}, {'id': 3, 'complete': 0}]
How can I break out of the nested loop once a project has been flagged as complete? 将项目标记为已完成后,如何摆脱嵌套循环? Is there another approach I should consider instead of working with the nested loop?
我应该考虑使用另一种方法而不是使用嵌套循环吗?
Why not something like: 为什么不这样:
cids = [c['id'] for c in completes]
for project in projects:
project["complete"] = project["id"] in cids
This will set project["complete"]
to True
or False
, which I suggest is better. 这会将
project["complete"]
为True
或False
,我建议这样做更好。 If you really need 1
and 0
, then: 如果您确实需要
1
和0
,那么:
project["complete"] = int(project["id"] in cids)
If you store them as a dict of dicts keyed by id versus an array of dicts, it becomes much easier (in my opinion): 如果将它们存储为以id为键的dict字典而不是dict数组,则存储起来会容易得多(我认为):
projects = [{'id': 1}, {'id': 2}, {'id': 3}]
completes = [{'id': 1}, {'id': 2}]
projects_dict = {}
for p in projects:
projects_dict[p['id']] = p
completes_dict = {}
for c in completes:
completes_dict[c['id']] = c
for k in projects_dict.keys():
projects_dict[k]['complete'] = int(k in completes_dict)
Of course instead of looping through completes, just add the 'complete' key wherever it is you create the 'completes' array of dicts. 当然,与其循环遍历完成,不如在创建dict的“ completes”数组的任何地方添加“ complete”键。
I can't comment, but what jimhark is saying is good, except I think you need to say something like 我无法发表评论,但吉姆哈克所说的是好的,但我认为您需要说些类似的话
for project in projects:
project['complete'] = project['id'] in (complete['id'] for complete in completes)
Edit: He has since changed his answer to be correct 编辑:从那以后他改变了答案是正确的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.