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

Python List Filtering

I have a data in list

PRODUCT = [
{
    "type": "PLAN A",
    "detail":  "ABC",
    "plans": [
        {
            "name": 'Monthly',
            "id": "",
        },
        {
            "name": 'Annually',
            "id": "",
        }
    ],
    }, {
        "type": 'PLAN B',
        "detail": 'XYZ',
        "plans": [{
            "name": 'Tri-Month',
            "id": "",
            },
        ],
 }]

I want to loop or iterate over this array and want to update id for example when in plans name is Monthly I want the id to be "abcxyz" when name is Annually I want the id to be "dvgssd" when the name is Tri-Month I want the id to be "abc123.

This is the initial list it has more data in it. I have tried multiple ways to achieve it but I get error.

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

>Solution :

It is a nested loop problem. The first thing you need to understand is there will be 2 different loops that will be used.

  1. For the product array.
  2. For the plans array.

In the first loop, you will get an object from the plans array, and in the second loop, you will set the ids.

Below is the code to help you understand.

for iterator in PRODUCT:
for plan in iterator["plans"]:
    if plan["name"] == "Monthly":
        plan["id"] = "abcxyz"
    if plan["name"] == "Annually":
        plan["id"] = "dvgssd"
    if plan["name"] == "Tri-Month":
        plan["id"] = "abc123"
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