Search code examples
pythoniteratornested-loops

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)

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.