Login
📚 Introduction to Python Programming
Chapters ▾
⇩ Download ▾

10.4 Conditionals and looping in dictionaries

Learning objectives

By the end of this section you should be able to

  • Write a conditional statement to check for a key/value.
  • Write a for loop to iterate over elements of a dictionary.

Conditionals for dictionary

Conditional statements can be used with dictionaries to check if certain keys, values, or dictionary items exist in the dictionary or if a value satisfies a particular condition.

Looping on a dictionary

Looping over a Python dictionary is a way to iterate through key-value pairs in the dictionary. Looping in a dictionary can be done by iterating over keys or items. When looping using keys, keys are obtained using the keys function and are passed to the loop variable one at a time. When looping over items using the items function, both the key and value for each item are passed to the loop variable.