I have this sample return json:
message_response_json = {"details": [
{
"orderId": "1",
"accountId": "1",
"orderStatus": "CANCELED"
},
{
"orderId": "2",
"accountId": "1",
"orderStatus": "SETTLED"
},
{
"orderId": "3",
"accountId": "1",
"orderStatus": "FUNDED"
},
{
"orderId": "4",
"accountId": "1",
"orderStatus": "FUNDED"
},
]}
I want to only get the list of orderIds
with the orderStatus
"FUNDED"
. This is the code I have so far:
details = message_response_json['details']
results = list(filter(lambda detail: detail['orderStatus'].lower() == "funded", details))
print('results', results)
This is what's printing:
results [{'orderId': '3', 'accountId': '1', 'orderStatus': 'FUNDED'}, {'orderId': '4', 'accountId': '1', 'orderStatus': 'FUNDED'}]
But I only ever want to get something like:
results [{'orderId': '3'}, {'orderId': '4'}]
or
results ['3', '4']
Is there a built-in map
function that I can use in python?
CodePudding user response:
You can use list-comprehension:
out = [
m["orderId"]
for m in message_response_json["details"]
if m["orderStatus"] == "FUNDED"
]
print(out)
Prints:
['3', '4']
Or:
out = [
{"oderId": m["orderId"]}
for m in message_response_json["details"]
if m["orderStatus"] == "FUNDED"
]
print(out)
for:
[{'oderId': '3'}, {'oderId': '4'}]
CodePudding user response:
If you want to use map and filter you can do
print(list(map(lambda s: {'orderId': s.get('orderId')}, filter(lambda s: s.get('orderStatus').lower() == 'funded', message_response_json.get('details')))))
It will filter details by status and then map them to wanted output