I have syntax error in this line:
data = [{'name': project['name'], 'id': project['id']} for projects in api.all_projects() project = projects.to_dict() if project['name'].startswith('name')]
I’m not sure where’s the problem.
Error message when I run the python cli:
>>> data = [{'name': project['name'], 'id': project['id']} for projects in api.all_projects() project = projects.to_dict() if project['name'].startswith('name')]
File "<stdin>", line 1
data = [{'name': project['name'], 'id': project['id']} for projects in api.all_projects() project = projects.to_dict() if project['name'].startswith('name')]
^^^^^^^
SyntaxError: invalid syntax
>Solution :
You can’t perform arbitrary assignment after the iteration statement; project = projects.to_dict() is not allowed where you put it.
You can use the walrus operator/assignment expression (:=) from 3.8+ as part of the if to achieve a similar effect though:
data = [{'name': project['name'], 'id': project['id']}
for projects in api.all_projects()
if (project := projects.to_dict())['name'].startswith('name')]
Other solutions, which avoid leaking the walrus-assigned variable, but are typically more verbose or ugly in one way or another, include:
-
Second loop over one-
tupleor one-elementlist:data = [{'name': project['name'], 'id': project['id']} for projects in api.all_projects() for project in [projects.to_dict()] # for project in (projects.to_dict(),) also works if (project['name'].startswith('name')] -
map-ing with known class’s method (if you actually know the class), oroperator.methodcaller:data = [{'name': project['name'], 'id': project['id']} for project in map(Project.to_dict, api.all_projects()) if (project['name'].startswith('name')] # Without knowing class from operator import methodcaller # At top of file data = [{'name': project['name'], 'id': project['id']} for project in map(methodcaller('to_dict'), api.all_projects()) if (project['name'].startswith('name')] -
chepner’s inner generator expression solution (a somewhat more verbose Python-level version of the
map-based solutions)