Home > OS >  How to loop(for) through data with conditions in python
How to loop(for) through data with conditions in python

Time:11-18

Example data:

[
    {
        "field_name": "mobile",
        "field_value": "917845546369",
        "type": "primary"
    },
    {
        "field_name": "email",
        "field_value": "[email protected]",
        "type": "primary"
    },
    {
        "field_name": "name",
        "field_value": "XYZ",
        "type": "primary"
    }
]

I need to loop through it and get the field_value field. The challenge is I need to get it based on field_name.

Expected result is get field_value

ex: if field_name=mobile
    mobile=field_value

mobile = 917845546369
email = [email protected]
name = XYZ

CodePudding user response:

You mean like:

data = [
    {
        "field_name": "mobile",
        "field_value": "917845546369",
        "type": "primary"
    },
    {
        "field_name": "email",
        "field_value": "[email protected]",
        "type": "primary"
    },
    {
        "field_name": "name",
        "field_value": "XYZ",
        "type": "primary"
    }
]

result = []
for k, i in enumerate(data):
    if some_condition(i):
       # This will include only the needed elements,
       # or you can "Nullify" any data[k]["field"] here instead
       result.append(i)

# or simply...

result = [i["field_name"] for i in data if some_condition(i)]

When some_condition(i) can be anything like i["field_value"] == 22 or foo(i) where foo returns a boolean.

  • Related