get only one value in element in array of elements python

Question:

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?

Asked By: Prosy Arceno

||

Answers:

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'}]
Answered By: Andrej Kesely

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

Answered By: sudden_appearance
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.