Skip to content
Advertisement

Create array of values in an if statement in Python

I want to create an array of values based on a condition.

data_total = [
    {"modele": "DS",
     "cote_actual": 10000},
    {"modele": "DS",
     "cote_actual": 12000},
    {"modele": "204",
     "cote_actual": 10000}]

for total in data_total:
    model = total["modele"]
    cote_actual = total["cote_actual"]
    model_ds = []

    if model == "DS":
        model_cote = cote_actual
        print(model_cote)
        model_ds.append(model_cote)
        print(model_ds)

The output I want:

"modele_ds" = [10000, 12000]

I mess with the loop, I don’t have the input I need. I know I have to append or populate the array.

Advertisement

Answer

As others said, you must assign model_ds list outside the loop, because having it inside the loop it gets empty with every iteration. Your code should be (line that changed is with comment):

data_total = [
    {"modele": "DS",
     "cote_actual": 10000},
    {"modele": "DS",
     "cote_actual": 12000},
    {"modele": "204",
     "cote_actual": 10000}]

model_ds = [] #assign model_ds outside the loop
for total in data_total:
    model = total["modele"]
    cote_actual = total["cote_actual"]
    if model == "DS":
        model_cote = cote_actual
        model_ds.append(model_cote)

Output:

>>> print(model_ds)

[10000, 12000]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement