10.7: Using Tuples as Keys in Dictionaries

Python for Everybody · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    10.7: Using Tuples as Keys in Dictionaries

    Because tuples are hashable and lists are not, if we want to create a composite key to use in a dictionary we must use a tuple as the key.

    We would encounter a composite key if we wanted to create a telephone directory that maps from last-name, first-name pairs to telephone numbers. Assuming that we have defined the variables last, first, and number, we could write a dictionary assignment statement as follows:

    directory[last,first] = number

    The expression in brackets is a tuple. We could use tuple assignment in a for loop to traverse this dictionary.

    for last, first in directory:
        print(first, last, directory[last,first])

    This loop traverses the keys in directory, which are tuples. It assigns the elements of each tuple to last and first, then prints the name and corresponding telephone number.


    This page titled 10.7: Using Tuples as Keys in Dictionaries was last modified on Tue, 01 Dec 2020 03:50:58 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Chuck Severance via source content that was edited to the style and standards of the LibreTexts platform.