Sets and Dictionaries

Table of Contents

  • Dictionaries

  • Estimated Time Needed: 20 min

    Dictionaries in Python

    A dictionary consists of keys and values. It is helpful to compare a dictionary to a list. Instead of the numerical indexes such as a list, dictionaries have keys. These keys are labels that are used to access values within a dictionary.

    A Comparison of a Dictionary to a list: Instead of the numerical indexes like a list, dictionaries have keys.

    An example of a Dictionary Dict:

    
    
    In [1]:
    Dict={"key1":1,"key2":"2","key3":[3,3,3],"key4":(4,4,4),('key5'):5,(0,1):6}
    Dict
    
    
    
    
    Out[1]:
    {(0, 1): 6,
     'key4': (4, 4, 4),
     'key2': '2',
     'key3': [3, 3, 3],
     'key1': 1,
     'key5': 5}

    The keys can be strings:

    
    
    In [2]:
    Dict["key1"]
    
    
    
    
    Out[2]:
    1

    Keys can also be any immutable object such as a tuple:

    
    
    In [3]:
    Dict[(0,1)]
    
    
    
    
    Out[3]:
    6

    Each key is separated from its value by a colon ":". Commas separate the items, and the whole dictionary is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this "{}".

    
    
    In [4]:
    release_year_dict = {"Thriller":"1982", "Back in Black":"1980", \
                        "The Dark Side of the Moon":"1973", "The Bodyguard":"1992", \
                        "Bat Out of Hell":"1977", "Their Greatest Hits (1971-1975)":"1976", \
                        "Saturday Night Fever":"1977", "Rumours":"1977"}
    release_year_dict
    
    
    
    
    Out[4]:
    {'Back in Black': '1980',
     'Bat Out of Hell': '1977',
     'Rumours': '1977',
     'Saturday Night Fever': '1977',
     'The Bodyguard': '1992',
     'The Dark Side of the Moon': '1973',
     'Their Greatest Hits (1971-1975)': '1976',
     'Thriller': '1982'}

    In summary, like a list, a dictionary holds a sequence of elements. Each element is represented by a key and its corresponding value. Dictionaries are created with two curly braces containing keys and values separated by a colon. For every key, there can only be a single value, however, multiple keys can hold the same value. Keys can only be strings, numbers, or tuples, but values can be any data type.

    It is helpful to visualize the dictionary as a table, as in figure 9. The first column represents the keys, the second column represents the values.

    Figure 9: Table representing a Dictionary

    </h4>

    You will need this dictionary for the next two questions :

    
    
    In [5]:
    soundtrack_dic = { "The Bodyguard":"1992", "Saturday Night Fever":"1977"}
    soundtrack_dic
    
    
    
    
    Out[5]:
    {'Saturday Night Fever': '1977', 'The Bodyguard': '1992'}

    In the dictionary "soundtrack_dict" what are the keys ?

    
    
    In [6]:
    soundtrack_dic.keys()
    
    
    
    
    Out[6]:
    dict_keys(['The Bodyguard', 'Saturday Night Fever'])
    ``` The Keys "The Bodyguard" and "Saturday Night Fever" ```

    In the dictionary "soundtrack_dict" what are the values ?

    ``` The values are "1992" and "1977" ```

    You can retrieve the values based on the names:

    
    
    In [7]:
    release_year_dict['Thriller']
    
    
    
    
    Out[7]:
    '1982'

    This corresponds to:

    Table used to represent accessing the value for "Thriller"

    </h4>

    Similarly for The Bodyguard

    
    
    In [8]:
    release_year_dict['The Bodyguard']
    
    
    
    
    Out[8]:
    '1992'

    Accessing the value for the "The Bodyguard"

    </h4>

    Now let us retrieve the keys of the dictionary using the method release_year_dict():

    
    
    In [9]:
    release_year_dict.keys()
    
    
    
    
    Out[9]:
    dict_keys(['The Dark Side of the Moon', 'Back in Black', 'Rumours', 'Bat Out of Hell', 'Their Greatest Hits (1971-1975)', 'The Bodyguard', 'Thriller', 'Saturday Night Fever'])

    You can retrieve the values using the method values():

    
    
    In [10]:
    release_year_dict.values()
    
    
    
    
    Out[10]:
    dict_values(['1973', '1980', '1977', '1977', '1976', '1992', '1982', '1977'])

    We can add an entry:

    
    
    In [11]:
    release_year_dict['Graduation']='2007'
    release_year_dict
    
    
    
    
    Out[11]:
    {'Back in Black': '1980',
     'Bat Out of Hell': '1977',
     'Graduation': '2007',
     'Rumours': '1977',
     'Saturday Night Fever': '1977',
     'The Bodyguard': '1992',
     'The Dark Side of the Moon': '1973',
     'Their Greatest Hits (1971-1975)': '1976',
     'Thriller': '1982'}

    We can delete an entry:

    
    
    In [12]:
    del(release_year_dict['Thriller'])
    del(release_year_dict['Graduation'])
    release_year_dict
    
    
    
    
    Out[12]:
    {'Back in Black': '1980',
     'Bat Out of Hell': '1977',
     'Rumours': '1977',
     'Saturday Night Fever': '1977',
     'The Bodyguard': '1992',
     'The Dark Side of the Moon': '1973',
     'Their Greatest Hits (1971-1975)': '1976'}

    We can verify if an element is in the dictionary:

    
    
    In [13]:
    'The Bodyguard' in release_year_dict
    
    
    
    
    Out[13]:
    True

    The Albums 'Back in Black', 'The Bodyguard' and 'Thriller' have the following music recording sales in millions 50, 50 and 65 respectively:

    a) Create a dictionary “album_sales_dict” where the keys are the album name and the sales in millions are the values.
    
    
    In [15]:
    album_sales_dict = {'Back in Black':50, 'The Bodygaurd':50, 'Thriller':65}
    
    ``` album_sales_dict= { "The Bodyguard":50, "Back in Black":50,"Thriller":65} ```

    b) Use the dictionary to find the total sales of "Thriller":

    
    
    In [16]:
    album_sales_dict['Thriller']
    
    
    
    
    Out[16]:
    65
    ``` album_sales_dict["Thriller"] ```

    c) Find the names of the albums from the dictionary using the method "keys":

    
    
    In [17]:
    album_sales_dict.keys()
    
    
    
    
    Out[17]:
    dict_keys(['Thriller', 'Back in Black', 'The Bodygaurd'])

    </div>

    album_sales_dict.keys()

    d) Find the names of the recording sales​ from the dictionary using the method "values":

    
    
    In [18]:
    album_sales_dict.values()
    
    
    
    
    Out[18]:
    dict_values([65, 50, 50])
    ``` album_sales_dict.values() ```

    About the Authors:

    Joseph Santarcangelo has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.


    Copyright © 2017 cognitiveclass.ai. This notebook and its source code are released under the terms of the MIT License.