Django Python Dictionary comprehension giving synt

2020-05-03 11:33发布

问题:

I was using dictionary comprehension in my Django app (tried in django shell as well) but is giving a syntax error. Here is a sample code.

>>> first_dict = {'a':1, 'b':2}
>>> second_dict = {}
>>> second_dict = {key: value for key, value in first_dict.iteritems()}
  File "<console>", line 1
second_dict = {key: value for key, value in first_dict.iteritems()}
                            ^

Yes, it is showing a ^ below for.

If I try the same outside the django shell, on a regular python shell, it works.

>>> first_dict = {'a':1, 'b':2}
>>> second_dict = {}
>>> second_dict = {key: value for key, value in first_dict.iteritems()}
>>> second_dict
{'a': 1, 'b': 2}

If I use iteration instead of dictionary comprehension, it works in django. Is this expected, or am I doing something wrong?

回答1:

Dictionary comprehensions are only in Python versions 2.7+, and it seems you are running Django under an earlier version.