问题描述
我在Django应用程序中使用了字典理解功能(也在django shell中尝试过),但是给出了语法错误.这是示例代码.
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.
如果我在django外壳之外尝试相同的操作,则在常规python外壳上可以正常工作.
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}
如果我使用迭代而不是字典理解,那么它将在Django中工作.这是预期的,还是我做错了什么?
If I use iteration instead of dictionary comprehension, it works in django. Is this expected, or am I doing something wrong?
推荐答案
词典理解仅在2.7+版本的Python中有效,并且看来您在Django的较早版本下运行.
Dictionary comprehensions are only in Python versions 2.7+, and it seems you are running Django under an earlier version.
这篇关于Django Python词典理解给出语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!