Home > Mobile >  How to print out if value exists else return False?
How to print out if value exists else return False?

Time:11-25

I have been working on a script that checks if there has been a new item added or if item has been increased. I have created a script like this:

STOCK_MAP = {
    'low': 1,
    'medium': 2,
    'high': 3
}

previous_data = {
    'item': {
        '1': 'HIGH',
        '2': 'HIGH',
        '3': 'HIGH',
        '4': 'MEDIUM',
    }
}

data = {
    'item': {
        '1': 'LOW',
        '2': 'HIGH',
        '3': 'HIGH',
        '4': 'HIGH',
        '5': 'HIGH',
    }
}


def check_changes(data: dict):
    found_change = {'new': [], 'increased': []}
    for att, value in data['item'].items():
        if not previous_data.get('item', {}).get(att, {}):
            found_change['new'].append(att)
        elif STOCK_MAP[value.casefold()] > STOCK_MAP[previous_data['item'][att].casefold()]:
            found_change['increased'].append(att)
    return found_change


if new_data := check_changes(data):
    print(new_data)

This script works right where it actually prints out whenever there is a new item added or/and if there has been a increasment. However if I change the previou data same as data = meaning like this:

previous_data = {
    'item': {
        '1': 'HIGH',
        '2': 'HIGH',
        '3': 'HIGH',
        '4': 'MEDIUM',
    }
}

data = {
    'item': {
        '1': 'HIGH',
        '2': 'HIGH',
        '3': 'HIGH',
        '4': 'MEDIUM',
    }


if new_data := check_changes(data):
    print(new_data)

Then it will returns "True" as there is a value that is being returned and I wonder how can I return "False" if there is no change in new item or increased?

Expect:

If there is a increasement or/and new item added. Then I want to print out:

Found Change! (Item Added: 1, 2, 3)  <-- Only if new Item has been added

Found Change! (Level Increased: 3, 4, 5) <--- Only if level increased

Found Change! (Item Added: 1, 2, 3 & Level Increased: 5, 6, 7) <-- If both values are true

and if there is no changes then return False

CodePudding user response:

Then it will returns "True" as there is a value that is being returned

no it won't return True, it will return an object/dict, always

I wonder how can I return "False" if there is no change in new item or increased?

how about

    if(len(found_change['new']) == 0 and len(found_change['increased']) == 0):
        return False
    return found_change

btw it seems strange that you are checking if they have increased, but you don't check if anything has decreased.

  • Related