python - Update list of dictionaries based on another list of dictionaries -
i have 2 lists of dictionaries, 1 list of project identifiers , other list of completed project identifiers. i'm looking add together key project identifier list, based on existence in completed list.
current code
>>> projects = [{'id': 1}, {'id': 2}, {'id': 3}] >>> completes = [{'id': 1}, {'id': 2}] >>> finish in completes: ... 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 break out of nested loop 1 time project has been flagged complete? there approach should consider instead of working nested loop?
edit - fixed (thanks @sotapme)
why not like:
cids = [c['id'] c in completes] project in projects: project["complete"] = project["id"] in cids
this set project["complete"]
true
or false
, suggest better. if need 1
, 0
, then:
project["complete"] = int(project["id"] in cids)
python python-2.7
No comments:
Post a Comment