Lesson 52 +10 XP

Loop Through Dictionaries

A plain for loop gives you the keys; other methods give you more.

Loop keys


python
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
for x in thisdict:
    print(x)

### brand, model, year

Loop keys explicitly


python
for x in thisdict.keys():
    print(x)

Loop values


python
for x in thisdict:
    print(thisdict[x])

Or use values():


python
for x in thisdict.values():
    print(x)

Loop both key and value


python
for x, y in thisdict.items():
    print(x, y)

TL;DR

  • for k in d iterates keys.
  • for k in d.keys() is explicit.
  • for v in d.values() iterates values.
  • for k, v in d.items() iterates both.