2016-09-09 73 views
-1

我有下面這段代碼在2.7工作正常,但在2.6轉換的Python 2.7的代碼到Python 2.6

def recursively_prune_dict_keys(obj, keep): 
    if isinstance(obj, dict): 
     return {k: recursively_prune_dict_keys(v, keep) for k, v in obj.items() if k in keep} 
    elif isinstance(obj, list): 
     return [recursively_prune_dict_keys(item, keep) for item in obj] 
    else: 
     return obj 

失敗,我得到無效的語法錯誤下面一行:

return {k: recursively_prune_dict_keys(v, keep) for k, v in obj.items() if k in keep} 

任何想法什麼需要改變,使其在2.6的工作?

+2

http://stackoverflow.com/questions/21069668/替代字典理解-python-2-7 – cel

回答

2

替換列表解析由呼叫包裹字典解析(未在Python 2.6支持和下文),以dict()

return dict([(k, recursively_prune_dict_keys(v, keep)) 
      for k, v in obj.items() if k in keep]) 
+0

需要注意的是,代碼使用了Python 2.7中引入的「dict comprehension」。簡單地手工構建字典就像這裏所做的那樣,就是修復。這是相關的[PEP 274](https://www.python.org/dev/peps/pep-0274/) – ffledgling