Mayur Randive
Mayur Randive

Reputation: 643

Failing to compare array of two objects in python

Can someone please please have a look at below code and help me debug whats going wrong, the code is expected to return

1
1 

but it is giving

1
0

Code

inputs  = [{'segment_id': 826502001, 'version': 'v2'},{'segment_id': 827768001, 'version': 'v1'}]

def ch():
    
    def function(segment_id,version):
        for item in inputs:
            if item['segment_id'] == segment_id and item['version'] == version:
                return 0
            else:
                return 1
    return function

def main():

    check = ch()
    print(check(827768001 , 'v1') ) 
    print(check(826502001,  'v2'))



if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        pass

Upvotes: 0

Views: 55

Answers (3)

Marmite Bomber
Marmite Bomber

Reputation: 21063

You may use the in membership operator to test if a dict is contained in the list.

Internally this will be resolved as an any check of the list members - see details in the link above.

inputs  = [{'segment_id': 826502001, 'version': 'v2'},{'segment_id': 827768001, 'version': 'v1'}]

def check(segment_id,version):
    return int({'segment_id': segment_id, 'version': version} in inputs)

print(check(827768001 , 'v1')) 
print(check(826502001,  'v2'))
print(check(827768001 , 'v3')) 

returns as expected

1
1
0

Upvotes: 1

alani
alani

Reputation: 13079

You want:

        for item in inputs:
            if item['segment_id'] == segment_id and item['version'] == version:
                return 1
        else:
            return 0

Or simply:

        for item in inputs:
            if item['segment_id'] == segment_id and item['version'] == version:
                return 1
        return 0

In other words, return 1 if any match, but if none match then return 0.


Addendum: it could also be done as a one-liner if you wanted:

return int(any(item['segment_id'] == segment_id and item['version'] == version for item in inputs))

Upvotes: 3

Gavin Wong
Gavin Wong

Reputation: 1260

This is because a function can only return one item, but you are trying to loop over 2 values and return 2 values in function().

You could append the values you want to return into a list, and then return the list instead.

Upvotes: 1

Related Questions