문제

this is a line from within Wagtail (Django variant CMS with very cool UI). The issue is it's written for Python 2.7 and I am using Python 2.6 with Django + FastCGI on shared hosting.

I've already changed a previous syntax error as spotted by mhlester but can't figure this one out:

>>> for attr in json_attrs
  File "<stdin>", line 1
    for attr in json_attrs
                          ^
SyntaxError: invalid syntax

the original code:

 if use_json: # Return a json response
        if search_results:
            search_results_json = []
            for result in search_results:
                result_specific = result.specific

                search_results_json.append({
                    attr: getattr(result_specific, attr)
                    for attr in json_attrs
                    if hasattr(result_specific, attr)
                })

any help please?

도움이 되었습니까?

해결책

There are no dictionary comprehensions in < Python 2.7. Instead you should pass a list of tuples to the dict() builtin.

dict((attr, getattr(result_specific, attr)) for attr in json_attrs if hasattr(result_specific, attr))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top