loader image
Skip to main content
If you continue browsing this website, you agree to our policies:
x

Topic outline

  • Unit 6: Basic Data Structures II – Tuples, Sets and Dictionaries

    Python's power lies not only in the vast set of modules and libraries available (such as matplotlib, random, math, numpy, etc.), but also in the data structures that are fundamental to the language. This unit introduces three more ways of structuring data that must be mastered: tuples, sets, and dictionaries. We will also revisit the concepts of mutability and immutability, as we saw for lists and strings.

    Completing this unit should take you approximately 3 hours.

    • Upon successful completion of this unit, you will be able to:

      • explain the difference between lists and tuples;
      • explain sets and apply set operations;
      • create dictionaries using dict; and
      • write programs that apply tuples, sets, and dictionaries.
    • 6.1: Immutable Collections

      • We have introduced the concepts of mutable and immutable objects in Python. Recall that lists are mutable while strings are immutable. This section introduces two more immutable data types useful for holding collections of objects: tuples and sets.

        In short, tuples are immutable lists. Similar to strings, they cannot be changed once they have been assigned. Everything that you have learned so far about indexing and slicing also applies to tuples. The syntax for forming a tuple uses parentheses (instead of square brackets for forming a list):

        a=[23.7, 45, 78]
        b='asdfasdf'
        c=(4,9,a,b,'zxcv')
        print(c)
        print(type(c))

        Notice that we can put any object we please into the tuple defined as the variable c. The output after running this code looks almost exactly like a list. However, because of the immutability of c, attempting to modify an element with an instruction such as c[1]=99will result in an error. One obvious use for tuples for holding data that must be write-protected. We will see other uses when we encounter dictionaries.

        Sets are another immutable data type that holds a unique collection of objects. Sets can be used to perform typical set operations such as union, intersection, set differences, and so on. Duplicates values are not possible within a set. Left and right squirrely brackets are used to assign sets.

        a={3,4,5,6,7,9}
        print(a)
        print(type(a))
        b={3,3,3,4,4,4,5,5,6,7,8}
        print(b)
        print(type(b))

        You should observe that both b and c contain the same set of objects. The next set of commands should demonstrate Python's ability to perform set operations.

        a={3,4,5}
        b={4,5,6,7,8,9}
        c=a.intersection(b)
        print(c)
        d=a.union(b)
        print(d)
        e=8
        print(e in b)
        print(e in a)
        f=b.difference(a)
        print(f)

        This code introduces fundamental operations such as set membership (using the in keyword) and a suite of set method calls for computing the union, intersection, and so on.

    • 6.2: Mutable Collections

      • Dictionaries structure data to allow for more interesting accessions beyond simple indexing. A given dictionary entry consists of both a key and a value. The key is then used as a means of accessing a value. This code shows how to create a dictionary and how to access values by using the key:

        adexamp={'NY':'Albany', 'CA': 'Sacramento','MA':'Boston'}
        print(adexamp)
        print(type(adexamp))

        The dictionary is of data type dict. Each entry is of the form key:value. A value in a dictionary is referenced by its key. The syntax for forming the dictionary requires using left and right curly brackets. It should never be confused with a set data type, as the syntax for the entries is completely different.

        Dictionary values are mutable; values can be referenced and modified by using the key.

        adexamp={'NY':'Albany', 'CA': 'Sacramento','MA':'Boston'}
        print(adexamp)
        print(type(adexamp))
         
        print(adexamp['NY'])		#value is referenced by the key
        adexamp['NY'] ='Buffalo'	#values are mutable
        print(adexamp['NY'])		#value is referenced by the key

        Notice how the "indexing" of the value occurs using the key. It is of extreme importance to note that, while values are mutable, keys are immutable. Any attempt to modify a key after a dictionary has been constructed will result in an error.

        However, dictionaries are mutable in the sense that we can add or remove entries.

        Continuing the example:

        adexamp['MD']='Annapolis'	#to add a single new entry
        print(adexamp)
        bdexamp={'AK':'Juneau', 'AZ':'Phoenix'}
        adexamp.update(bdexamp)	#add several new entries
        print(adexamp)
        del adexamp['MA']
        print(adexamp)

        This example shows the syntax for adding a single entry by invoking a new key. To add several entries, it is more efficient to use a dict method called update. The del command is one way to remove an entry by referencing a specific key. This section will give you more insight into using Python dictionaries.

      • Read this for more on dictionaries.
      • One major application of dictionaries is to be able to efficiently sequence through a set of values. Read this section to practice writing loops using dictionaries.
      • Another application of tuples is to use them as keys in dictionaries. Follow and practice the examples presented in this section in order to understand how tuples can be used with dictionaries.
    • 6.3: A Comprehensive Review of Data Structures

      • We have introduced several basic Python data structures: lists, strings, sets, tuples and dictionaries. Take some time to review, compare and contrast these constructs for handling various kinds of collections.


    • Study Session Video Review

    • Unit 6 Review and Assessment

      • In this video, course designer Eric Sakk walks through the major topics we covered in Unit 6. As you watch, work through the exercises to try them out yourself.

      • Take this assessment to see how well you understood this unit.

        • This assessment does not count towards your grade. It is just for practice!
        • You will see the correct answers when you submit your answers. Use this to help you study for the final exam!
        • You can take this assessment as many times as you want, whenever you want.