代码在python 2.6下无效,但在2.7中很好

yee*_*379 -1 python syntax python-2.6 python-2.7

有人可以帮我翻译一些python 2.7语法到python 2.6请(由于redhat依赖,有点卡在2.6)

所以我有一个简单的功能来构建一个树:

def tree(): return defaultdict(tree)
Run Code Online (Sandbox Code Playgroud)

当然我想以某种方式显示树.在python 2.7下我可以使用:

$ /usr/bin/python2.7
Python 2.7.2 (default, Oct 17 2012, 03:00:49)
[GCC 4.4.6 [TWW]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def dicts(t): return {k: dicts(t[k]) for k in t}
...
>>>
Run Code Online (Sandbox Code Playgroud)

一切都很好...但在2.6以下我得到以下错误:

$ /usr/bin/python
Python 2.6.6 (r266:84292, Sep  4 2013, 07:46:00)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def dicts(t): return {k: dicts(t[k]) for k in t}
  File "<stdin>", line 1
    def dicts(t): return {k: dicts(t[k]) for k in t}
                                           ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

我怎么能重写代码:

def dicts(t): return {k: dicts(t[k]) for k in t}
Run Code Online (Sandbox Code Playgroud)

这样我可以在python 2.6下使用它?

Joh*_*ooy 6

你必须用dict()传递生成器表达式来替换dict理解.即.

def dicts(t): return dict((k, dicts(t[k])) for k in t)
Run Code Online (Sandbox Code Playgroud)