You have 3 free guides left 😟
Unlock your guides
You have 3 free guides left 😟
Unlock your guides

10.4 Conditionals and looping in dictionaries

3 min readjune 24, 2024

Dictionaries Python offer powerful tools data manipulation. Conditional checks and looping techniques allow you to search, filter, and process contents efficiently. These methods are essential for working with complex data structures in real-world programming scenarios.

Advanced operations take your skills further. Dictionary comprehensions and enable you to create and modify dictionaries based on specific conditions. These techniques streamline your code and enhance your ability to work with structured data.

Conditionals and Looping in Dictionaries

Conditional checks in dictionaries

Top images from around the web for Conditional checks in dictionaries
Top images from around the web for Conditional checks in dictionaries
  • Check a key exists in a dictionary using the
    in
    keyword
    • Evaluates to
      [True](https://www.fiveableKeyTerm:TRUE)
      if the key is found,
      [False](https://www.fiveableKeyTerm:FALSE)
      otherwise
    • Example:
      if 'name' in student_info:
  • Check if a value exists in a dictionary by iterating through the
    [values()](https://www.fiveableKeyTerm:values())
    view
    • values()
      returns a view object containing all the values in the dictionary
    • Iterate through the view to find a specific value
    • Example:
      if 'John' in student_info.values():
  • Use the
    [get()](https://www.fiveableKeyTerm:get())
    method to retrieve the value associated with a key, providing a default value if the key is not found
    • Syntax:
      dictionary.get(key, default_value)
    • Returns the value if the key exists, otherwise returns the default value
    • Example:
      age = student_info.get('age', 18)
  • Use for concise key-value checks
    • Example:
      result = 'Adult' if age >= 18 else 'Minor'

Iteration through dictionary components

  • Iterate through dictionary keys using a
    for
    loop
    • By default, iterating over a dictionary yields its keys
    • Access the corresponding value using the key within the loop
    • Example:
      for name in phone_book:
          print(name, phone_book[name])
      
  • Iterate through dictionary values using the
    values()
    method
    • values()
      returns a view object containing all the values in the dictionary
    • Useful when only the values are needed, not the keys
    • Example:
      for phone_number in phone_book.values():
          print(phone_number)
      
  • Iterate through dictionary using the
    [items()](https://www.fiveableKeyTerm:items())
    method
    • items()
      returns a view object containing tuples of key-value pairs
    • Unpack the tuple in the
      for
      loop to access both the key and value
    • Example:
      for name, phone_number in phone_book.items():
          print(name, phone_number)
      
  • Use to process
    • Example:
      for department, employees in company.items():
          for employee, details in employees.items():
              print(f"{employee} works in {department}")
      

Application of dictionary methods

  • Use the
    [keys()](https://www.fiveableKeyTerm:keys())
    method to get a view of all keys in the dictionary
    • Useful for checking the existence of keys or iterating through them
    • Example:
      if 'address' in student_info.keys():
  • Use the
    values()
    method to get a view of all values in the dictionary
    • Useful for checking the existence of values or iterating through them
    • Example:
      for grade in student_grades.values():
          if grade >= 90:
              print("A")
      
  • Use the
    items()
    method to get a view of all key-value pairs as tuples
    • Useful for iterating through both keys and values simultaneously
    • Example:
      for item, price in store_inventory.items():
          if price > 100:
              print(item, "is expensive")
      
  • Combine dictionary methods with conditional statements
    • Check for specific keys or values while iterating through a dictionary
    • Example:
      for name, score in exam_scores.items():
          if score < 60:
              print(name, "failed the exam")
      

Advanced dictionary operations

  • Use for creating dictionaries based on conditions
    • Example:
      squared_numbers = {x: x**2 for x in range(10) if x % 2 == 0}
  • Apply boolean operators in dictionary operations
    • Example:
      valid_entries = {k: v for k, v in data.items() if v is not None and v != ''}
  • Utilize conditional expressions in dictionary comprehensions
    • Example:
      grade_status = {name: 'Pass' if score >= 60 else 'Fail' for name, score in exam_scores.items()}
© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.


© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.

© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.
Glossary
Glossary