-1

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?

Frederico Martins
  • 1,081
  • 1
  • 12
  • 25
user3646519
  • 353
  • 5
  • 15
  • 2
    http://stackoverflow.com/questions/21069668/alternative-to-dict-comprehension-prior-to-python-2-7 – cel Sep 09 '16 at 15:40

1 Answers1

2

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])
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • The point of note is that the code uses a `dict comprehension` which were introduced in python 2.7. Simply constructing a dictionary by hand as done here, is the fix. Here's the relevant [PEP 274](https://www.python.org/dev/peps/pep-0274/) – ffledgling Sep 09 '16 at 15:46