Home > database >  How to skip Index count using enumerate when value is zero?
How to skip Index count using enumerate when value is zero?

Time:12-02

I have currently one dict with key-value and one list with values. e.g.

data = {
    'total': {
        '06724': 0,
        '06725': 0,
        '06726': 0,
        '06727': 0,
        '06712': 22,
        '06713': 35,
        '06714': 108,
        '06715': 70,
        '06716': 0,
        '06717': 24,
        '06718': 0,
        '06719': 0,
        '06720': 0,
        '06709': 75,
        '06710': 123,
        '06711': 224,
        '06708': 28,
        '06723': 0,
        '06721': 0,
        '06722': 0
    },
    'item_number': ['1', '2', '3', '4', '5', '6', '7', '8', '9']
}

for Index, value in enumerate(data['total'].values()):
    if value and value != '0':
        print(data['item_number'][Index], value)

What I am trying to do is that I want to remove all values in 'total' that has the value 0 meaning that it would only end up being 9 numbers which adds up to the item_number amount.

What I am trying to achieve is that I want print out:

Expected:

{
    '1': 22,
    '2': 35,
    '3': 108,
    '4': 70,
    '5': 24,
    '6': 75,
    '7': 123,
    '8': 224,
    '9': 28
}

where key is the item_number and the value is total.

However the code I am currently trying gives me the error:

    print(data['item_number'][Index], value)
IndexError: list index out of range

which I believe is due to the Index increasing for each loop. I wonder how can I skip the counting increase if the value is 0?

CodePudding user response:

If I understand you correctly:

out = dict(
    zip(data["item_number"], (v for v in data["total"].values() if v != 0))
)
print(out)

Prints:

{
    "1": 22,
    "2": 35,
    "3": 108,
    "4": 70,
    "5": 24,
    "6": 75,
    "7": 123,
    "8": 224,
    "9": 28,
}

CodePudding user response:

Either use a count variable instead of enumerate(), or filter before enumerating.

Count variable

index = 0
for value in data['total'].values():
    if value != 0:
        print((data['item_number'][index], value))
        index  = 1

Output:

('1', 22)
('2', 35)
('3', 108)
('4', 70)
('5', 24)
('6', 75)
('7', 123)
('8', 224)
('9', 28)

Filter first

for index, value in enumerate(v for v in data['total'].values() if v != 0):
    print((data['item_number'][index], value))

(Same output)

And this can be simplified further using zip() like in Andrej's answer.


Note: I'm not using a dict here for simplicity and because your code as posted doesn't use one. I think it's obvious how you would incorporate one though.

  • Related