-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
  • 23,859
  • 5
  • 60
  • 99
Yash
  • 369
  • 5
  • 18

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
  • 35,554
  • 7
  • 89
  • 134
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
  • 757
  • 8
  • 29