Skip to main content
Engineering LibreTexts

10.4: Conditionals and Looping in Dictionaries

  • Page ID
    117588
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\dsum}{\displaystyle\sum\limits} \)

    \( \newcommand{\dint}{\displaystyle\int\limits} \)

    \( \newcommand{\dlim}{\displaystyle\lim\limits} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \(\newcommand{\longvect}{\overrightarrow}\)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\ket}[1]{\left| #1 \right>}\)
    \(\newcommand{\bra}[1]{\left< #1 \right|}\)
    \(\newcommand{\braket}[2]{\left< #1 \vphantom{#2} \right| \left. #2 \vphantom{#1} \right>}\)
    \(\newcommand{\braopket}[3]{\left< #1 \vphantom{#2}\vphantom{#3} \right| #2 \vphantom{#1}\vphantom{#3} \left| #3 \vphantom{#1}\vphantom{#2} \right>}\)
    \(\newcommand{\qmvec}[1]{\mathbf{\vec{#1}}}\)
    \(\newcommand{\op}[1]{\hat{\mathbf{#1}}}\)
    \(\newcommand{\expect}[1]{\langle #1 \rangle}\)
    \(\newcommand{\dfn}[1]{\emph{\textbf{#1}}}\)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)
    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.

    Example 10.2: Templates and examples of a conditional statement on a dictionary
    Table 10.1
    dict.items()
    # (key, value) in dictionary.items()
    
    movies = {"The godfather": 1974, "Interstellar": 2014}
    
    print(("Interstellar", 2014) in movies.items())
    

    True

    Table 10.2
    Conditionals on values or keys
    # dictionary[key] operand test_value
    
    movies = {"The godfather": 1974, "Interstellar": 2014}
    
    print(movies["The godfather"] < 2000)
    

    True

    Table 10.3
    dict.keys()
    # key in dictionary.keys()
    
    movies = {"The godfather": 1974, "Interstellar": 2014}
    
    print("Interstellar" in movies.keys())
    

    True

    Table 10.4
    dict.values()
    # value in dictionary.values()
    
    movies = {"The godfather": 1974, "Interstellar": 2014}
    
    print(2014 in movies.values())
    

    True

    Concepts in Practice \(\PageIndex{1}\): Conditionals on Dictionaries

    Given the dictionary fruit_count = {"apple": 2, "orange": 5, "pomegranate": 1}, what is the output of "apple" in fruit_count.keys() ?

    1. True
    2. False
    Answer

    a. "apple" is a key in the dictionary and exists in the returned keys from fruit_count.keys().

    Concepts in Practice \(\PageIndex{2}\): Conditionals on Dictionaries

    Given the dictionary fruit_count = {"apple": 2, "orange": 5, "pomegranate": 1}, what is the output of ("orange", 5) in fruit_count.items()?

    1. SyntaxError
    2. True
    3. False
    Answer

    b. The key "orange" , with associated value 5 , exists in the dictionary and the return value is True .

    Concepts in Practice \(\PageIndex{3}\): Conditionals on Dictionaries

    Given the dictionary fruit_count = {"apple": 2, "orange": 5, "pomegranate": 1}, which conditional statement checks if the value associated with the key "pomegranate" is greater than 0?

    1. fruit_count("pomegranate") > 0
    2. fruit_count["pomegranate"] > 0
    3. fruit_count.get("pomegranate" > 0)
    Answer

    b. Conditional statements can be written to examine keys and values.

    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.

    A for loop over a dictionary retrieves each key in the dictionary
        for key in dictionary: # Loop expression
          # Statements to execute in the loop
    
        # Statements to execute after the loop
    Example 10.3: Iterating over a dictionary
    Table 10.5
    dict.items()
    zip_codes = {"Berkeley": 94709, "Santa Cruz": 95064, "Mountain View": 94030}
    
    for key, value in zip_codes.items():
      print(key, value)
    
    Berkeley 94709
    Santa Cruz 95064
    Mountain View 94030
    Table 10.6
    dict.keys()
    zip_codes = {"Berkeley": 94709, "Santa Cruz": 95064, "Mountain View": 94030}
    
    for key in zip_codes.keys():
      print(key)
    
    Berkeley
    Santa Cruz
    Mountain View
    
    Table 10.7
    dict.values()
    zip_codes = {"Berkeley": 94709, "Santa Cruz": 95064, "Mountain View": 94030}
    
    for value in zip_codes.values():
      print(value)
    
    94709
    95064
    94030
    
    Concepts in Practice \(\PageIndex{4}\): Loops on dictionaries

    Which method is used to loop over the values in a Python dictionary?

    1. keys()
    2. values()
    3. items()
    Answer

    b. The values() method iterates over values in a dictionary.

    Concepts in Practice \(\PageIndex{5}\): Loops on dictionaries

    What is the output of the following code?

    fruit_count = {"apple": 2, "orange": 5, "banana": 1}
    for key in fruit_count.keys():
      print(key, end = " ")
    1. apple orange banana
    2. 2 5 1
    3. ("apple", 2) ("orange", 5) ("banana", 1)
    Answer

    a. The loop iterates over the keys "apple" , "orange" , and "banana" , and prints the keys space-separated.

    Concepts in Practice \(\PageIndex{6}\): Loops on dictionaries

    What is the output of the following code?

    fruit_count = {"apple": 2, "orange": 5, "banana": 1}
    for value in fruit_count.values():
      print(value * 2, end = " ")
    1. apple orange banana
    2. 2 5 1
    3. 4 10 2
    Answer

    c. The loop multiplies all values by 2 and prints the output. So, 4 , 10 , and 2 are printed.

    Try It: Character count in a string

    Given a string value, calculate and print the number of occurrences of all characters using a dictionary.

        Input:
        string_value = "This is a string"
        Prints {"T": 1, "h": 1, "i": 3, "s": 3, " ": 3, "a": 1, "t": 1, "r": 1, "n": 1, 
        "g": 1}
    
    string_value = "This is a string"
    
    # Create a dictionary and count the number of occurrences of characters
     
    Answer

    string_value = "This is a string"
    characters = {}

    for c in string_value:
    if c in characters.keys():
    characters[c] += 1
    else:
    characters[c] = 1

    print(characters)

    Try It: Calculate the total number of fruits

    Given a fruit_count dictionary that contains information about fruits and the count of each fruit, calculate the total number of fruits across all fruit types.

        Input:
        fruit_count = {"banana": 2, "orange": 5, "peach": 5}
        Prints 12    
    
    fruit_count = {"banana": 2, "orange": 5, "peach": 5}
    
    # Calculate and print the total number of fruits
     
    Answer
    fruit_count = {"banana": 2, "orange": 5, "peach": 5}
    
    total_count = 0
    for count in fruit_count.values():
        total_count += count
    
    print(total_count)
    

    This page titled 10.4: Conditionals and Looping in Dictionaries was last modified on Fri, 24 Jul 2026 08:47:33 GMT and is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.