This question is related to this one. What's a Pythonic way to map a function to a given level specification.

Level specification should support slices, to map to multiple levels or say -1 (leaf nodes).

This is applicable to hierarchical combinations of dict, list or iterables - for example as obtained from deserializing JSON.


data = [{'a': 1, 'b': {'c':[2,3]}},{'a':10,'b':{'c':[12,13]}}]

for example _map(f,data,-1)

should return

[{'a': f(1), 'b': {'c':[f(2),f(3)]}},{'a':f(10),'b':{'c':[f(12),f(13)]}}]

_map(f,data,[2,3]) should return:

[{'a': f(1), 'b': f({'c':f([2,3])}}),{'a':f(10),'b':f({'c':f([12,13])})}]

Are there utilities in ast package that can facilitate this?

The screenshot shows the corresponding and a couple more examples in Wolfram Language where level spec is an option to map:

enter image description here


Here is a practical illustration. Given this directory structure, how to filter out the OSX files '.DS_Store' which can occur in most folders?

{'Data': {'.DS_Store': '~/Data/.DS_Store',
  'Folder2': {'file3.rtf': '~/Data/Folder2/file3.rtf'},
  'Folder1': {'file0.rtf': '~/Data/Folder1/file0.rtf',
   '.DS_Store': '~/Data/Folder1/.DS_Store',
   'Folder13': {},
   'Folder12': {'file2.rtf': '~/Data/Folder1/Folder12/file2.rtf',
    'file1.rtf': '~/Data/Folder1/Folder12/file1.rtf',
    '.DS_Store': '~/Data/Folder1/Folder12/.DS_Store'}}}}

0 Answers