1
thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]

How do I say:

If "red" is in thelist and time does not equal 2 for that element (that's we just got from the list):
1
  • Is there a difference in speed between "wallacoloo" answer and the list comprehension/pythonic answers? Commented Jan 13, 2010 at 0:28

6 Answers 6

13

Using any() to find out if there is an element satisfying the conditions:

>>> any(item['color'] == 'red' and item['time'] != 2  for item in thelist)
False
Sign up to request clarification or add additional context in comments.

3 Comments

this is nice! Am I understanding it correctly that the parentheses of the any() are doubling as a generator, so any() evaluates the list comprehension item by item and will return True once it finds an item that satisfies the criteria?
It's a "generator expression", available in reasonably reason version of python (since 2.4). One could also write any([...]) to get a classical list comprehension. (see python.org/dev/peps/pep-0289 for more on generator expressions)
That's the kind of stuff that makes me love Python.
1
def colorRedAndTimeNotEqualTo2(thelist):
    for i in thelist:
        if i["color"] == "red" and i["time"] != 2:
            return True
    return False

print colorRedAndTimeNotEqualTo2([{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}])

for i in thelist iterates through thelist, assigning the current element to i and doing the rest of the code in the block (for each value of i)

Thanks for the catch, Benson.

2 Comments

beaten to the punch by 30 seconds-- this is exactly what I would do. Except, just to be in the python 3 habit: print(i)
That's workable, but the use of a for loop means that if there was more than one element with color == red and time != 2 you'd get I printed twice.
0

Well, there's nothing as elegant as "find" but you can use a list comprehension:

matches = [x for x in thelist if x["color"] == "red" and x["time"] != 2]
if len(matches):
    m = matches[0]
    # do something with m

However, I find the [0] and len() tedious. I often use a for loop with an array slice, such as:

matches = [x for x in thelist if x["color"] == "red" and x["time"] != 2]
for m in matches[:1]:
    # do something with m

1 Comment

I was assuming an "at most one" kind of find. If you want all matches, I'd defer to someone else's answer.
0
list = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]
for i in list:
  if i['color'] == 'red' && i['time'] != 2:
    print i

2 Comments

Perhaps this is too nitpicky, but I recommend you avoid naming things "list", because you may at some point need access to the list constructor and it would be a shame to have overwritten it.
Python uses "and" instead of "&&"
0
for val in thelist:
    if val['color'] == 'red' and val['time'] != 2:
        #do something here

But it doesn't look like that's the right data structure to use.

Comments

0

You can do most of the list manipulation in a list comprehension. Here's one that makes a list of times for all elements where the color is red. Then you can ask if 2 exists in those times.

thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]
reds = ( x['time'] == 2 for x in thelist if x['color'] == red )
if False in reds:
  do_stuff()

You can condense that even further by eliminating the variable "reds" like this:

thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]
if False in ( x['time'] == 2 for x in thelist if x['color'] == red ):
  do_stuff()

2 Comments

this requires 2 searches instead of 1 (one to get the element, another to find False). this also needs more ram (the list comprehension could generate a huge result). iterating would be more efficient
I switched to generator comprehensions rather than list comprehensions, since (as jspcal said) the lists were unnecessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.