根据另一个词典列表更新词典列表

时间:2013-02-07 19:26:18

标签: python python-2.7

我有两个词典列表,一个是项目标识符列表,另一个是已完成项目标识符列表。我希望根据已完成列表中的存在,为项目标识符列表添加一个键。

当前代码

>>> 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}]

预期输出

[{'id': 1, 'complete': 1}, {'id': 2, 'complete': 1}, {'id': 3, 'complete': 0}]

一旦项目被标记为完成,我怎样才能打破嵌套循环?是否有其他方法我应该考虑而不是使用嵌套循环?

3 个答案:

答案 0 :(得分:3)

编辑 - 修复(感谢@sotapme)

为什么不能这样:

cids = [c['id'] for c in completes]
for project in projects:
    project["complete"] = project["id"] in cids

这会将project["complete"]设置为TrueFalse,我建议这样做会更好。如果您确实需要10,那么:

    project["complete"] = int(project["id"] in cids)

答案 1 :(得分:1)

如果你将它们存储为由id和一系列dicts键入的dicts的词典,它会变得更容易(在我看来):

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)

当然,不是循环完成,只需添加'完整'键即可创建完整的'完成'数组。

答案 2 :(得分:1)

我不能发表评论,但是jimhark所说的是好的,除了我认为你需要说的话

for project in projects:
    project['complete'] = project['id'] in (complete['id'] for complete in completes)

编辑:他已经改变了他的答案是正确的