Here's my Python code
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
for x in thisdict:
print(x)
It outputs:
brand
model
year
I can't understand the logic!!
Here's my Python code
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
for x in thisdict:
print(x)
It outputs:
brand
model
year
I can't understand the logic!!
for a in b
iterates through b
by calling iter(b)
first to get an iterator of b
, and repeatedly calling next()
on the iterator and assigning the values to a
before running the loop body.
An iterator of a python dictionary generates all its keys, so you're getting all keys of thisdict
with x
in your loop and printing them.
The for loop loops through the keys in the dictionary. To loop through and get the values of each key you could do (Try it online):
for x in thisdict:
print(thisdict[x])
and it would output:
Ford
Mustang
2018