2

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?

2 Answers 2

3

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'}]
Sign up to request clarification or add additional context in comments.

2 Comments

Is this better than using filter and map?
@ProsyArceno That's opinion based. Myself I prefer list-comprehension. But for more discussion visit here: stackoverflow.com/questions/3013449/…
1

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

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.