Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get only one value in element in array of elements python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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'}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading