-1

i am a new programmer trying to learn how to code still. I still don't quite know all of the technical info. I am trying to use a for loop on a list of dictionaries, and then inside of that loop, i want to create another loop that enumerates the dictionary keys. Inside of that loop, I then want to print the keys and values. I want the loop to break once the index reaches all of the points.

Dogs_in_Shelter = [{
               "type" : "poodle",
               "age" : "2", 
               "size" : "s", 
               
           }, 
           {    
               "type" : "pug",
               "age" : "7", 
               "size" : "m", 
           },
           {
               "type" : "lab",
               "age" : "10",
               "size" : "m", 
           }
               ]
for a in Dogs_in_Shelter:
 for index, a in enumerate(Dogs_in_Shelter):
   while (index <= 2): 
     print("{} {}".format(index,a["type"]))
     index += 1 
     break

what prints out is:

0 poodle
1 pug
2 lab
0 poodle
1 pug
2 lab
0 poodle
1 pug
2 lab

I want only the first three lines (with the key and value) , not the repetitions. Any help for a learner?

edit Yes there is an easier way without the nesting loops however i still need to have them nested. Thanks!

robert
  • 1
  • 1
  • If you don't want repetitions you should get rid of the extra `for` and `while` loops. You only need one `for` loop: `for i, d in enumerate(Dogs_in_Shelter): print(i, d["type"])` – Selcuk Mar 09 '21 at 01:46

2 Answers2

1

No need of extra for loop and while loop. enumerate function gives you index and by passing type key you can get its value.

for index, a in enumerate(Dogs_in_Shelter):
    print("{} {}".format(index, a["type"]))

Using nesting for loop.

Here I have used counter length = 0. Instead of while we should use if to check the counter.

length = 0
for a in Dogs_in_Shelter:
 for index, a in enumerate(Dogs_in_Shelter):
     if length <= 2 :
        print("{} {}".format(index,a["type"]))
        length += 1
Rima
  • 1,447
  • 1
  • 6
  • 12
  • thank you for the suggestion, but i would still like to use the extra nested loops to complete this. Any other suggestions? TIA – robert Mar 09 '21 at 02:02
  • what is the purpose of extra loop? – Rima Mar 09 '21 at 02:03
  • while loop inside for loop will give repetitive result. Instead use if- statement to check condition. I have updated answer. – Rima Mar 09 '21 at 02:30
0
  1. You only need one for loop for what you want. while loop is also unnecessary. For example,
for index, dog in enumerate(Dogs_in_Shelter):
    print(index, dog['type'])
  1. For Python, we don't use upper letters for variables. FYI, Python Naming Convention In this case, Dogs_in_Shelter should be dogs_in_shelter, or simply dogs.
Jaybe Park
  • 172
  • 1
  • 5