-4

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!!

Peter Wood
  • 22,682
  • 5
  • 57
  • 94
Yash
  • 311
  • 3
  • 17

2 Answers2

1

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.

iBug
  • 32,728
  • 7
  • 79
  • 117
0

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
Noah Cristino
  • 735
  • 8
  • 29