Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Could someone please explain why this works? (Python Iterator)

I have a dictionary with some pet names and their corresponding info and a list with owner names. The goal of the code is to update the dictionary by extracting a name from a list (owners) and create a new key : value pair in the dictionary.

owners = ["adam", "sandra", "ashley"]
pets = {
"buster": {
    "type": "dog",
    "colour": "black and white",
    "disposition": "sassy",
},
"jojo": {
    "type": "cat",
    "colour": "grey",
    "disposition": "grumpy",
},
"amber": {"type": "cat", "colour": "black", "disposition": "playful"},

}

iterator = iter(pets.values())
for owner in owners:
    for pet_info in iterator:
        try:
            pet_info["owner"] = owner
            break
        except StopIteration:
            print("The end")
print(pets)



Output

{
'buster': {'type': 'dog', 'colour': 'black and white', 'disposition': 'sassy', 'owner': 'adam'}, 
'jojo': {'type': 'cat', 'colour': 'grey', 'disposition': 'grumpy', 'owner': 'sandra'}, 
'amber': {'type': 'cat', 'colour': 'black', 'disposition': 'playful', 'owner': 'ashley'}
}

After using the iter() function, I was able to produce the output I desired. Hence, I am trying to figure out how the iter() function made this possible.
(I did google but the search results were not what I was looking for)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance !

>Solution :

pet.values() is a list while iter(pet.values()) gives you a list_iterator.
Check following example:

a=[1,2,3]
ia = iter(a)

for i in a:
    print(i)
    break

for i in a:
    print(i)
    break

for i in a:
    print(i)
    break

for i in ia:
    print(i)
    break


for i in ia:
    print(i)
    break

for i in ia:
    print(i)
    break

The output just explains the situation you may have ignored when using iter() func.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading