Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if value exists in python list of objects

if i have a simple list objects:

shapes = [
  {
    'shape': 'square',
    'width': 40,
    'height': 40
  },
  {
    'shape': 'rectangle',
    'width': 30,
    'height': 40

  }
]

How can i quickly check if a shape with value square exists? I know I can use a for loop to check each object, but is there a faster way?

Thanks in advance!

like image 739
Trung Tran Avatar asked Sep 10 '17 02:09

Trung Tran


People also ask

How do I check if an item exists in a list?

Check if element exist in list using list. count(element) function returns the occurrence count of given element in the list. If its greater than 0, it means given element exists in list.

How do you check if a variable is in a list Python?

Check if Variable is a List with type() Now, to alter code flow programatically, based on the results of this function: a_list = [1, 2, 3, 4, 5] # Checks if the variable "a_list" is a list if type(a_list) == list: print("Variable is a list.") else: print("Variable is not a list.")

How do you check if an element is not present in a list Python?

In & Not in operators “not in” operator − This operator is used to check whether an element is not present in the passed list or not. Returns true if the element is not present in the list otherwise returns false.

How do you check if a string is present in a list Python?

We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1. count(s) if count > 0: print(f'{s} is present in the list for {count} times.


6 Answers

You can do this in one line with the builtin function any:

if any(obj['shape'] == 'square' for obj in shapes):
    print('There is a square')

This is equivalent to the for-loop approach, though.


If you need to get the index instead, then there is still a one-liner that can do this without sacrificing efficiency:

index = next((i for i, obj in enumerate(shapes) if obj['shape'] == 'square'), -1)

However, this is complicated enough that it's probably better to just stick with a normal for loop.

index = -1
for i, obj in enumerate(shapes):
    if obj['shape'] == 'square':
        index = i
        break
like image 108
Eric Zhang Avatar answered Oct 04 '22 15:10

Eric Zhang


Look ma, no loop.

import json
import re

if re.search('"shape": "square"', json.dumps(shapes), re.M):
    ... # "square" does exist

If you want to retrieve the index associated with square, you'd need to iterate over it using for...else:

for i, d in enumerate(shapes):
    if d['shape'] == 'square':
        break
else:
    i = -1

print(i) 

Performance

100000 loops, best of 3: 10.5 µs per loop   # regex
1000000 loops, best of 3: 341 ns per loop   # loop
like image 41
cs95 Avatar answered Oct 04 '22 13:10

cs95


Using list comprehension you can do:

if [item for item in shapes if item['shape'] == 'square']:
    # do something

Using filter():

if list(filter(lambda item: item['shape'] == 'square', shapes)):
    # do something
like image 40
ettanany Avatar answered Oct 04 '22 15:10

ettanany


You can try this, using get for a more robust solution:

if any(i.get("shape", "none") == "square" for i in shapes):
    #do something
    pass
like image 42
Ajax1234 Avatar answered Oct 04 '22 15:10

Ajax1234


Checking only if it exists:

any(shape.get('shape') == 'square' for shape in shapes)

Getting first index (you will get StopIteration exception if it does not exist).

next(i for i, shape in enumerate(shapes) if shape.get('shape') == 'square')

All indexes:

[i for i, shape in enumerate(shapes) if shape.get('shape') == 'square']
like image 41
stachel Avatar answered Oct 04 '22 14:10

stachel


import operator
shape = operator.itemgetter('shape')
shapez = map(shape, shapes)
print('square' in shapez)
like image 29
wwii Avatar answered Oct 04 '22 13:10

wwii