'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 1:[1]
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.
Solution 2:[2]
You can do it like this providing the number of keys in 'pets' is identical to the number of elements in 'owners':
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"}}
for p, o in zip(pets.values(), owners):
p['owner'] = o
print(pets)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eric2i |
| Solution 2 |
