0

Im new to python and Im looking for a lambda solution to extract a dictionary with a dictionary along with filtering selected keys.

Example: My input is like below

 {'executionInfos': [
    {
      'cancelRequested': False,
      'execution': {'runId': 22CXalf3g9xdl7kts45gaagL0SdEYMTqockoag4LaBDc=',
                   'workflowId': 'TestWf1'},
      'executionStatus': 'OPEN',
      'startTimestamp': datetime.datetime(2019, 4, 25, 17, 1, 8, 585000, tzinfo=tzlocal()),
      'workflowType': {'name': 'Test',
                      'version': '1.0'}
    },
    {
      'cancelRequested': False,
      'execution': {'runId': 22NwIvCxrizJQescq7rLILHtMl9ktxj343DC7unUq2GK7M=',
                   'workflowId': TestWf2'},
      'executionStatus': 'OPEN',
      'startTimestamp': datetime.datetime(2019, 4, 12, 14, 19, 13, 837000, tzinfo=tzlocal()),
      'workflowType': {'name': 'Test',
                      'version': 1.0'}
    }
  ]
}

Im want to get a array of dict where i can filter keys on each dict(executionStatus) and extract keys from sub dict (workflowId) as well

 {'executionInfos': [
    {
      'workflowId': 'TestWf1',
      'executionStatus': OPEN',
    },
    {
      'workflowId': 'TestWf2',
      'executionStatus': OPEN',
    }
  ]
}

I know it can be done with if else conditions and looping but want to know how can it be done using lambda/ or any one-two liners. I tried below and dint work

KEYS_TO_FILTER = ['executionStatus','workflowId']
res2 = map(lambda attr: attr.keys(), response["executionInfos"])
res3 = filter(lambda attr: attr in KEYS_TO_FILTER, res2)

1 Answer 1

1

You can just create a new vacant dictionary and then use list comprehension. Here is a solution without using lambda function :

d = {'executionInfos': [...]}
d_ = {}
d_['executionInfos'] = [{'workflowId' : k['execution']['workflowId'], 'executionStatus' : k['executionStatus']} for k in d['executionInfos']]

OUTPUT :

{'executionInfos': [
    {'workflowId': 'TestWf1', 'executionStatus': 'OPEN'}, 
    {'workflowId': 'TestWf2', 'executionStatus': 'OPEN'}]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.