user3646519 user3646519 - 2 months ago 9
Python Question

Convert Python 2.7 code to Python 2.6

I have the following piece of code which works fine in 2.7 but fails in 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


I get invalid syntax error for line below:

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


Any idea what needs to change to make it work in 2.6?

Answer

Replace the dictionary comprehension (which is not supported in Python 2.6 and below) with a list comprehension wrapped by a call to dict():

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