How to yield key and value in a dictionary if conditional is met

78 Views Asked by At

Here is my current code

guests = {'Jane': 35, 'Kyle': 20, 'Justin': 43, 'Ayla': 22}

age_check = (key, value for key, value in guests.items() if value >= 21)
for guest in age_check:
  print(guest)

I am curious how I would get the output of every key and value where the value is over than or equal to 21 using a generator expression.

I have tried the code that is shown above which returns a SyntaxError. I have also tried returning both the key and value but only iterating through the values which also returned a SyntaxError. I have also tried a few miniscule changes but am currently stumped. I am assuming both the value and the key have to be mentioned after the if but am unsure how or where.

Any help would be much appreciated. Thank you in advance.

1

There are 1 best solutions below

0
tdelaney On BEST ANSWER

From Displays for lists, sets and dictionaries: The comprehension consists of a single expression followed by at least one for clause. In your case, the expression key, value is ambiguous in this context (is that a tuple being generated or is the second value in the tuple a generator) so must be encased in parentheses.

age_check = ((key, value) for key, value in guests.items() if value >= 21)