I'm a beginner and need some help. I need to use a for loop with break and continue to find the first person that has a dog in a list. The iteration count should not exceed 2.
Here is the given list:
people = [
{'name': "Daniel", 'age': 29, 'job': "Engineer", 'pet': "Cat", 'pet_name': "Gato"},
{'name': "Katie", 'age': 30, 'job': "Teacher", 'pet': "Dog", 'pet_name': "Frank"},
{'name': "Owen", 'age': 26, 'job': "Sales person", 'pet': "Cat", 'pet_name': "Cosmo"},
{'name': "Josh", 'age': 22, 'job': "Student", 'pet': "Cat", 'pet_name': "Chat"},
{'name': "Estelle", 'age': 35, 'job': "French Diplomat", 'pet': "Dog", 'pet_name': "Gabby"},
{'name': "Gustav", 'age': 24, 'job': "Brewer", 'pet': "Dog", 'pet_name': "Helen"}
]
and the following code was given to start:
first_dog_person = None
iteration_count = 0
for value in people:
iteration_count = 1
My thought process is using an if statement to iterate through the first two keys and find the value that equals "Dog". But I can't visualize it in my head to enter the code.
I've also learned how to create an empty list for ex. first_dog_person = [] and append key, value pairs to the new list but I can't figure out how to make the element equal the key (first_dog_person = None).
CodePudding user response:
Try using if statement, like in example below:
first_dog_person = None
iteration_count = 0
for value in people:
iteration_count = 1
# To ensure that iteration won't exceed 2
if iteration_count == 2:
break
if value['pet'] == 'Dog':
first_dog_person = value
If you want to check key value for a current dictionary item, simply just pass it in square brackets like
value['pet']
in example above.
After making sure that your item value meets the requirements, you can simply assign it to the created variable "first_dog_person".
Be sure to check out Python Docs and read about some Data Structures — Dictionary