Copyright © 2017 IBM Cognitive Class. This notebook and its source code are released under the terms of the MIT License.

Why Python:

  • The most popular, high level, open source programming language
  • Powerful
  • Fast
  • Dynamic programming
  • Interactive
  • Object-oriented
  • Easy to learn
  • Complete library for fast all purpose (analytics, gamimg, web, robots etc)

Module 2 - Python Data Structures

-LISTS AND TUPLES:

QUICK PRACTICE LAB

QUESTION 1
how do you access the last element of the tuple: A=(0,1,2,3) :

In [6]:
A=(0,1,2,3)
In [7]:
A[3]
Out[7]:
3
In [8]:
A[-1]
Out[8]:
3

QUESTION 2 (1 point possible)

Consider the list B=["a","b","c"]

what is the result of the following B[1:]

In [12]:
B=["a","b","c"]
In [13]:
B[1:]
Out[13]:
['b', 'c']
In [14]:
B[:1]
Out[14]:
['a']
In [15]:
B[1]
Out[15]:
'b'
In [16]:
B[:2]
Out[16]:
['a', 'b']
In [17]:
B[2:]
Out[17]:
['c']
In [18]:
# B[Start:End]

-LAB TUPLES

TUPLES IN PYTHON

About the Dataset

Table of Contents

  • About the Dataset
  • Tuples
  • Quiz on Tuples
  • Estimated Time Needed: 15 min

    Imagine you received album recommendations from your friends and compiled all of the recomendations into a table, with specific information about each album.

    The table has one row for each movie and several columns:

    • artist - Name of the artist
    • album - Name of the album
    • released_year - Year the album was released
    • length_min_sec - Length of the album (hours,minutes,seconds)
    • genre - Genre of the album
    • music_recording_sales_millions - Music recording sales (millions in USD) on SONG://DATABASE
    • claimed_sales_millions - Album's claimed sales (millions in USD) on SONG://DATABASE
    • date_released - Date on which the album was released
    • soundtrack - Indicates if the album is the movie soundtrack (Y) or (N)
    • rating_of_friends - Indicates the rating from your friends from 1 to 10

    The dataset can be seen below:

    <table font-size:xx-small style="width:25%"> Artist Album Released Length Genre Music recording sales (millions) Claimed sales (millions) Released Soundtrack Rating (friends) Michael Jackson Thriller 1982 00:42:19 Pop, rock, R&B 46 65 30-Nov-82 10.0 AC/DC Back in Black 1980 00:42:11 Hard rock 26.1 50 25-Jul-80 8.5 Pink Floyd The Dark Side of the Moon 1973 00:42:49 Progressive rock 24.2 45 01-Mar-73 9.5 Whitney Houston The Bodyguard 1992 00:57:44 Soundtrack/R&B, soul, pop 26.1 50 25-Jul-80 Y 7.0 Meat Loaf Bat Out of Hell 1977 00:46:33 Hard rock, progressive rock 20.6 43 21-Oct-77 7.0 Eagles Their Greatest Hits (1971-1975) 1976 00:43:08 Rock, soft rock, folk rock 32.2 42 17-Feb-76 9.5 Bee Gees Saturday Night Fever 1977 1:15:54 Disco 20.6 40 15-Nov-77 Y 9.0 Fleetwood Mac Rumours 1977 00:40:01 Soft rock 27.9 40 04-Feb-77 9.5 </table></font>

    Tuples

    In Python, there are different data types: string, integer and float. These data types can all be contained in a tuple as follows:

    <img src = "https://ibm.box.com/shared/static/t2jw5ia78ulp8twr71j6q7055hykz10c.png" width = 750, align = "center"></a>

    In [26]:
    tuple1=("disco",10,1.2 )
    tuple1
    
    Out[26]:
    ('disco', 10, 1.2)
    In [27]:
    tuple1=("disco",10,1.2 )
    tuple1
    
    Out[27]:
    ('disco', 10, 1.2)

    The type of variable is a tuple.

    In [29]:
     type(tuple1)
    
    Out[29]:
    tuple

    Each element of a tuple can be accessed via an index. The following table represents the relationship between the index and the items in the tuple. Each element can be obtained by the name of the tuple followed by a square bracket with the index number:

    <img src = "https://ibm.box.com/shared/static/83kpang0opwen5e5gbwck6ktqw7btwoe.gif" width = 750, align = "center"></a>

    We can print out each value in the tuple:

    In [33]:
    print( tuple1[0])
    print( tuple1[1])
    print( tuple1[2])
    
    disco
    10
    1.2
    

    We can print out the type of each value in the tuple:

    In [35]:
    print( type(tuple1[0]))
    print( type(tuple1[1]))
    print( type(tuple1[2]))
    
    <class 'str'>
    <class 'int'>
    <class 'float'>
    

    We can also use negative indexing. We use the same table above with corresponding negative values:

    <img src = "https://ibm.box.com/shared/static/uwlfzo367bekwg0p5s5odxlz7vhpojyj.png" width = 750, align = "center"></a>

    We can obtain the last element as follows (this time we will not use the print statement to display the values):

    In [39]:
    tuple1[-1]
    
    Out[39]:
    1.2

    We can display the next two elements as follows:

    In [41]:
    tuple1[-2]
    
    Out[41]:
    10
    In [42]:
    tuple1[-3]
    
    Out[42]:
    'disco'

    We can concatenate or combine tuples by using the + sign:

    In [44]:
    tuple2=tuple1+("hard rock", 10)
    tuple2
    
    Out[44]:
    ('disco', 10, 1.2, 'hard rock', 10)

    We can slice tuples obtaining multiple values as demonstrated by the figure below:

    <img src = "https://ibm.box.com/shared/static/s9nofy728bcnsgnx3vh159bu16w7frnc.gif" width = 750, align = "center"></a>

    We can slice tuples, obtaining new tuples with the corresponding elements:

    In [48]:
    tuple2[0:3]
    
    Out[48]:
    ('disco', 10, 1.2)

    We can obtain the last two elements of the tuple:

    In [50]:
    tuple2[3:5]
    
    Out[50]:
    ('hard rock', 10)

    We can obtain the length of a tuple using the length command:

    In [52]:
    len(tuple2)
    
    Out[52]:
    5

    This figure shows the number of elements:

    <img src = "https://ibm.box.com/shared/static/apxe8l3w42f597yjhizg305merlm4ijf.png" width = 750, align = "center"></a>

    Consider the following tuple:

    In [4]:
    Ratings  =(0,9,6,5,10,8,9,6,2)
    

    We can assign the tuple to a 2nd variable:

    In [6]:
    Ratings1=Ratings
    Ratings
    
    Out[6]:
    (0, 9, 6, 5, 10, 8, 9, 6, 2)

    We can sort the values in a tuple and save it to a new tuple:

    In [8]:
    RatingsSorted=sorted(Ratings )
    RatingsSorted
    
    Out[8]:
    [0, 2, 5, 6, 6, 8, 9, 9, 10]

    A tuple can contain another tuple as well as other more complex data types. This process is called 'nesting'. Consider the following tuple with several elements:

    In [10]:
    NestedT =(1, 2, ("pop", "rock") ,(3,4),("disco",(1,2)))
    

    The following figure shows the relationship of the tree and the element NestedT[4][1][1]:

    <img src ='https://ibm.box.com/shared/static/9y5s7515zwzc9v6i4f67yj3np2fv9evs.gif' width = 750, align = "center"></a>

    Quiz on Tuples

    Consider the following tuple:

    In [15]:
    genres_tuple = ("pop", "rock", "soul", "hard rock", "soft rock", \
                    "R&B", "progressive rock", "disco") 
    genres_tuple
    
    Out[15]:
    ('pop',
     'rock',
     'soul',
     'hard rock',
     'soft rock',
     'R&B',
     'progressive rock',
     'disco')

    Find the length of the tuple, "genres_tuple":

    In [18]:
    len(genres_tuple)
    
    Out[18]:
    8

    Access the element, with respect to index 3:

    In [20]:
    genres_tuple[3]
    
    Out[20]:
    'hard rock'

    Use slicing to obtain indexes 3, 4 and 5:

    In [22]:
    genres_tuple[3:6]
    
    Out[22]:
    ('hard rock', 'soft rock', 'R&B')

    Find the first two elements of the tuple "genres_tuple":

    In [24]:
    genres_tuple[0:2]
    
    Out[24]:
    ('pop', 'rock')

    Find the first index of 'disco':

    In [26]:
    genres_tuple.index("disco")
    
    Out[26]:
    7

    Generate a sorted List from the Tuple C_tuple=(-5,1,-3):

    In [28]:
    C_tuple = (-5,1,-3)
    C_list = sorted(C_tuple)
    C_list
    
    Out[28]:
    [-5, -3, 1]

    [Tip] Saving the Notebook

    Your notebook saves automatically every two minutes. You can manually save by going to **File** > **Save and Checkpoint**. You can come back to this notebook anytime by clicking this notebook under the "**Recent Notebooks**" list on the right-hand side.

    [Tip] Notebook Features

    Did you know there are other **notebook options**? Click on the **>** symbol to the left of the notebook:


    -LAB LISTS

    LISTS IN PYTHON

    Table of Contents

  • About the Dataset
  • Lists
  • Quiz

  • Estimated Time Needed: 15 min

    About the Dataset

    Imagine you received many music recommendations from your friends and compiled all of the recommendations into a table, with specific information about each movie.

    The table has one row for each album and several columns:

    • artist - Name of the artist
    • album - Name of the album
    • released_year - Year the album was released
    • length_min_sec - Length of the album (hours,minutes,seconds)
    • genre - Genre of the album
    • music_recording_sales_millions - Music recording sales (millions in USD) on SONG://DATABASE
    • claimed_sales_millions - Album's claimed sales (millions in USD) on SONG://DATABASE
    • date_released - Date on which the album was released
    • soundtrack - Indicates if the album is the movie soundtrack (Y) or (N)
    • rating_of_friends - Indicates the rating from your friends from 1 to 10

    The dataset can be seen below:

    <table font-size:xx-small style="width:25%"> Artist Album Released Length Genre Music recording sales (millions) Claimed sales (millions) Released Soundtrack Rating (friends) Michael Jackson Thriller 1982 00:42:19 Pop, rock, R&B 46 65 30-Nov-82 10.0 AC/DC Back in Black 1980 00:42:11 Hard rock 26.1 50 25-Jul-80 8.5 Pink Floyd The Dark Side of the Moon 1973 00:42:49 Progressive rock 24.2 45 01-Mar-73 9.5 Whitney Houston The Bodyguard 1992 00:57:44 Soundtrack/R&B, soul, pop 26.1 50 25-Jul-80 Y 7.0 Meat Loaf Bat Out of Hell 1977 00:46:33 Hard rock, progressive rock 20.6 43 21-Oct-77 7.0 Eagles Their Greatest Hits (1971-1975) 1976 00:43:08 Rock, soft rock, folk rock 32.2 42 17-Feb-76 9.5 Bee Gees Saturday Night Fever 1977 1:15:54 Disco 20.6 40 15-Nov-77 Y 9.0 Fleetwood Mac Rumours 1977 00:40:01 Soft rock 27.9 40 04-Feb-77 9.5 </table></font>

    Lists

    We are going to take a look at lists in Python. A list is a sequenced collection of different objects such as integers, strings, and other lists as well. The address of each element within a list is called an 'index'. An index is used to access and refer to items within a list.

    Representation of a list

    To create a list, type the list within square brackets [ ], with your content inside the parenthesis and separated by commas. Let’s try it!

    In [38]:
    L=["Michael Jackson" , 10.1,1982]
    L
    
    Out[38]:
    ['Michael Jackson', 10.1, 1982]

    We can use negative and regular indexing with a list :

    Representation of a list

    In [41]:
    print('the same element using negative and positive indexing:\n Postive:',L[0],
    '\n Negative:' , L[-3]  )
    print('the same element using negative and positive indexing:\n Postive:',L[1],
    '\n Negative:' , L[-2]  )
    print('the same element using negative and positive indexing:\n Postive:',L[2],
    '\n Negative:' , L[-1]  )
    
    the same element using negative and positive indexing:
     Postive: Michael Jackson 
     Negative: Michael Jackson
    the same element using negative and positive indexing:
     Postive: 10.1 
     Negative: 10.1
    the same element using negative and positive indexing:
     Postive: 1982 
     Negative: 1982
    

    Lists can contain strings, floats, and integers. We can nest other lists, and we can also nest tuples and other data structures. The same indexing conventions apply for nesting:

    In [43]:
    [ "Michael Jackson", 10.1,1982,[1,2],("A",1) ]
    
    Out[43]:
    ['Michael Jackson', 10.1, 1982, [1, 2], ('A', 1)]

    We can also perform slicing in lists. For example, if we want the last two elements, we use the following command:

    In [45]:
    L=[ "Michael Jackson", 10.1,1982,"MJ",1]
    L
    
    Out[45]:
    ['Michael Jackson', 10.1, 1982, 'MJ', 1]

    Representation of a list

    In [47]:
    L[3:5]
    
    Out[47]:
    ['MJ', 1]

    We can use the method "extend" to add new elements to the list:

    In [49]:
    L=[ "Michael Jackson", 10.2]
    L.extend(['pop',10])
    L
    
    Out[49]:
    ['Michael Jackson', 10.2, 'pop', 10]

    Another similar method is 'appended'. If we apply 'appended' instead of 'extended', we add one element to the list:

    In [51]:
    L=[ "Michael Jackson", 10.2]
    L.append(['pop',10])
    L
    
    Out[51]:
    ['Michael Jackson', 10.2, ['pop', 10]]

    Each time we apply a method, the list changes. If we apply "extend" we add two new elements to the list. The list L is then modified by adding two new elements:

    In [53]:
    L=[ "Michael Jackson", 10.2]
    L.extend(['pop',10])
    L
    
    Out[53]:
    ['Michael Jackson', 10.2, 'pop', 10]

    If we append the list ['a','b'] we have one new element consisting of a nested list:

    In [55]:
    L.append(['a','b'])
    L
    
    Out[55]:
    ['Michael Jackson', 10.2, 'pop', 10, ['a', 'b']]

    As lists are mutable, we can change them. For example, we can change the first element as follows:

    In [57]:
    A=["disco",10,1.2]
    print('Before change:', A)
    A[0]='hard rock'
    print('After change:', A)
    
    Before change: ['disco', 10, 1.2]
    After change: ['hard rock', 10, 1.2]
    

    We can also delete an element of a list using the del command:

    In [59]:
    print('Before change:', A)
    del(A[0])
    print('After change:', A)
    
    Before change: ['hard rock', 10, 1.2]
    After change: [10, 1.2]
    

    We can convert a string to a list using 'split'. For example, the method split translates every group of characters separated by a space into an element in a list:

    In [61]:
    'hard rock'.split()
    
    Out[61]:
    ['hard', 'rock']

    We can use the split function to separate strings on a specific character. We pass the character we would like to split on into the argument, which in this case is a comma. The result is a list, and each element corresponds to a set of characters that have been separated by a comma:

    In [63]:
    'A,B,C,D'.split(',')
    
    Out[63]:
    ['A', 'B', 'C', 'D']

    When we set one variable B equal to A; both A and B are referencing the same list in memory :

    In [65]:
    A=["hard rock",10,1.2]
    B=A
    print('A:',A)
    print('B:',B)
    
    A: ['hard rock', 10, 1.2]
    B: ['hard rock', 10, 1.2]
    

    Initially, the value of the first element in B is set as hard rock. If we change the first element in A to 'banana', we get an unexpected side effect. As A and B are referencing the same list, if we change list A, then list B also changes. If we check the first element of B we get banana instead of hard rock:

    In [68]:
    print('B[0]:',B[0])
    A[0]="banana"
    print('B[0]:',B[0])
    
    B[0]: hard rock
    B[0]: banana
    

    This is demonstrated in the following figure:

    You can clone list A by using the following syntax:

    In [73]:
    B=A[:]
    B
    
    Out[73]:
    ['banana', 10, 1.2]

    Variable B references a new copy or clone of the original list; this is demonstrated in the following figure:

    Now if you change A, B will not change:

    In [77]:
    print('B[0]:',B[0])
    A[0]="banana"
    print('B[0]:',B[0])
    
    B[0]: banana
    B[0]: banana
    

    Quiz

    Create a list 'a_list' , with the following elements 1, “hello”, [1,2,3 ] and True.

    In [80]:
    a_list=[1, 'hello', [1,2,3 ] , True]
    a_list
    
    Out[80]:
    [1, 'hello', [1, 2, 3], True]

    Find the value stored at index 1 of 'a_list'.

    In [82]:
    a_list[1]
    
    Out[82]:
    'hello'

    Retrieve the elements stored at index 1,2, and 3 of 'a_list'.

    Concatenate the following lists A=[1,'a'] abd B=[2,1,'d']:

    A=[1,'a'] 
    B=[2,1,'d']
    A+B

    -SETS

    QUICK PRACTICE LAB

    QUESTION 1

    What is the result of the following lines of code:

    In [4]:
    S={'A','B','C'}
    
    U={'A','Z','C'}
    
    U.union(S)
    
    Out[4]:
    {'A', 'B', 'C', 'Z'}

    QUESTION 2

    What is the intersection of set S and U

    In [11]:
    S={'A','B','C'}
    
    U={'A','Z','C'}
    
    In [13]:
    S.intersection(U)
    
    Out[13]:
    {'A', 'C'}

    -LAB SETS

    Sets and Dictionaries

    Table of Contents

  • Sets

  • Estimated Time Needed: 20 min

    Sets

    In this lab, we are going to take a look at sets in Python. A set is a unique collection of objects in Python. You can denote a set with a curly bracket {}. Python will remove duplicate items:

    In [18]:
    set1={"pop", "rock", "soul", "hard rock", "rock", "R&B", "rock", "disco"}
    set1
    
    Out[18]:
    {'R&B', 'disco', 'hard rock', 'pop', 'rock', 'soul'}

    The process of mapping is illustrated in the figure:

    You can also create a set from a list as follows:

    In [22]:
    album_list =[ "Michael Jackson", "Thriller", 1982, "00:42:19", \
                  "Pop, Rock, R&B", 46.0, 65, "30-Nov-82", None, 10.0]
    
    album_set = set(album_list)             
    album_set
    
    Out[22]:
    {'00:42:19',
     10.0,
     1982,
     '30-Nov-82',
     46.0,
     65,
     'Michael Jackson',
     None,
     'Pop, Rock, R&B',
     'Thriller'}

    Now let us create a set of genres:

    In [24]:
    music_genres = set(["pop", "pop", "rock", "folk rock", "hard rock", "soul", \
                        "progressive rock", "soft rock", "R&B", "disco"])
    music_genres
    
    Out[24]:
    {'R&B',
     'disco',
     'folk rock',
     'hard rock',
     'pop',
     'progressive rock',
     'rock',
     'soft rock',
     'soul'}

    Convert the following list to a set ['rap','house','electronic music', 'rap']:

    In [26]:
    set(['rap','house','electronic music','rap'])
    
    Out[26]:
    {'electronic music', 'house', 'rap'}

    Notice that the duplicates are removed and the output is sorted.

    Let us get the sum of the claimed sales:

    Consider the list A=[1,2,2,1] and set B=set([1,2,2,1]), does sum(A)=sum(B)

    In [31]:
    A=[1,2,2,1]  
    B=set([1,2,2,1])
    print("the sum of A is:",sum(A))
    print("the sum of B is:",sum(B))
    
    the sum of A is: 6
    the sum of B is: 3
    

    Now let's determine the average rating:

    In [37]:
    sum(A)/len(A)
    
    Out[37]:
    1.5
    In [36]:
    sum(B)/len(B)
    
    Out[36]:
    1.5

    Set Operations

    Let us go over Set Operations, as these can be used to change the set. Consider the set A:

    In [40]:
    A = set(["Thriller","Back in Black", "AC/DC"] )
    A
    
    Out[40]:
    {'AC/DC', 'Back in Black', 'Thriller'}

    We can add an element to a set using the add() method:

    In [42]:
    A.add("NSYNC")
    A
    
    Out[42]:
    {'AC/DC', 'Back in Black', 'NSYNC', 'Thriller'}

    If we add the same element twice, nothing will happen as there can be no duplicates in a set:

    In [44]:
    A.add("NSYNC")
    A
    
    Out[44]:
    {'AC/DC', 'Back in Black', 'NSYNC', 'Thriller'}

    We can remove an item from a set using the remove method:

    In [46]:
    A.remove("NSYNC")
    A
    
    Out[46]:
    {'AC/DC', 'Back in Black', 'Thriller'}

    We can verify if an element is in the set using the in command :

    In [48]:
    "AC/DC"  in A
    
    Out[48]:
    True

    Working with sets

    Remember that with sets you can check the difference between sets, as well as the symmetric difference, intersection, and union:

    Consider the following two sets:

    In [52]:
    album_set1 = set(["Thriller",'AC/DC', 'Back in Black'] )
    album_set2 = set([ "AC/DC","Back in Black", "The Dark Side of the Moon"] )
    

    Visualizing the sets as two circles

    </h4>

    In [54]:
    album_set1, album_set2
    
    Out[54]:
    ({'AC/DC', 'Back in Black', 'Thriller'},
     {'AC/DC', 'Back in Black', 'The Dark Side of the Moon'})

    As both sets contain 'AC/DC' and 'Back in Black' we represent these common elements with the intersection of two circles.

    Visualizing common elements with the intersection of two circles.

    </h4>

    We can find the common elements of the sets as follows:

    In [58]:
    album_set_3=album_set1 & album_set2
    album_set_3
    
    Out[58]:
    {'AC/DC', 'Back in Black'}

    We can find all the elements that are only contained in album_set1 using the difference method:

    In [60]:
    album_set1.difference(album_set2)  
    
    Out[60]:
    {'Thriller'}

    We only consider elements in album_set1; all the elements in album_set2, including the intersection, are not included.

    The difference of “album_set1” and “album_set2

    </h4>

    The difference between album_set2 and album_set1 is given by:

    In [64]:
    album_set2.difference(album_set1)  
    
    Out[64]:
    {'The Dark Side of the Moon'}

    The difference of album_set2 and album_set1

    </h4>

    We can also find the intersection, i.e in both album_list2 and album_list1, using the intersection command :

    In [67]:
    album_set1.intersection(album_set2)   
    
    Out[67]:
    {'AC/DC', 'Back in Black'}

    This corresponds to the intersection of the two circles:

    Intersection of set

    </h4>

    The union corresponds to all the elements in both sets, which is represented by colouring both circles:

    Figure 7: Union of set

    </h4>

    The union is given by:

    In [73]:
    album_set1.union(album_set2)
    
    Out[73]:
    {'AC/DC', 'Back in Black', 'The Dark Side of the Moon', 'Thriller'}

    And you can check if a set is a superset or subset of another set, respectively, like this:

    In [75]:
    set(album_set1).issuperset(album_set2)   
    
    Out[75]:
    False
    In [76]:
    set(album_set2).issubset(album_set1)     
    
    Out[76]:
    False

    Here is an example where issubset() is issuperset() is true:

    In [78]:
    set({"Back in Black", "AC/DC"}).issubset(album_set1) 
    
    Out[78]:
    True
    In [79]:
    album_set1.issuperset({"Back in Black", "AC/DC"})   
    
    Out[79]:
    True

    Create a new set “album_set3” that is the union of “album_set1” and “album_set2”:

    In [81]:
    album_set3=album_set1.union(album_set2)
    album_set3
    
    Out[81]:
    {'AC/DC', 'Back in Black', 'The Dark Side of the Moon', 'Thriller'}

    Find out if "album_set1" is a subset of "album_set3":

    In [83]:
    album_set1.issubset(album_set3)
    
    Out[83]:
    True

    -DICTIONARIES

    In [ ]:
    QUICK PRACTICE LAB
    

    QUESTION 1 (1 point possible) Consider the following dictionary:

    D={'a':0,'b':1,'c':2}

    What is the result of the following: D.values()

    In [86]:
    D={'a':0,'b':1,'c':2}
    
    In [87]:
    D.values()
    
    Out[87]:
    dict_values([0, 1, 2])

    QUESTION 2

    Consider the following dictionary:

    D={'a':0,'b':1,'c':2} What is the output of the following D['b'] :

    In [91]:
    D={'a':0,'b':1,'c':2}
    
    In [92]:
    D['b']
    
    Out[92]:
    1

    -LAB DICTIONARIES

    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 [5]:
    Dict={"key1":1,"key2":"2","key3":[3,3,3],"key4":(4,4,4),('key5'):5,(0,1):6}
    Dict
    
    Out[5]:
    {'key1': 1,
     'key2': '2',
     'key3': [3, 3, 3],
     'key4': (4, 4, 4),
     'key5': 5,
     (0, 1): 6}

    The keys can be strings:

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

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

    In [9]:
    Dict[(0,1)]
    
    Out[9]:
    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 [11]:
    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[11]:
    {'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'}

    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 [32]:
    soundtrack_dict = { "The Bodyguard":"1992", "Saturday Night Fever":"1977"}
    soundtrack_dict
    
    Out[32]:
    {'The Bodyguard': '1992', 'Saturday Night Fever': '1977'}

    In the dictionary "soundtrack_dic" what are the keys ?

    In [18]:
    #The Keys "The Bodyguard" and "Saturday Night Fever" 
    

    In the dictionary "soundtrack_dict" what are the values ?

    In [20]:
    #The values are "1992" and "1977"
    

    You can retrieve the values based on the names:

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

    This corresponds to:

    Table used to represent accessing the value for "Thriller"

    </h4>

    Similarly for The Bodyguard

    In [26]:
    release_year_dict['The Bodyguard'] 
    
    Out[26]:
    '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 [31]:
    release_year_dict.keys() 
    
    Out[31]:
    dict_keys(['Thriller', 'Back in Black', 'The Dark Side of the Moon', 'The Bodyguard', 'Bat Out of Hell', 'Their Greatest Hits (1971-1975)', 'Saturday Night Fever', 'Rumours'])

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

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

    We can add an entry:

    In [36]:
    release_year_dict['Graduation']='2007'
    release_year_dict
    
    Out[36]:
    {'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',
     'Graduation': '2007'}

    We can delete an entry:

    In [38]:
    del(release_year_dict['Thriller'])
    del(release_year_dict['Graduation'])
    release_year_dict
    
    Out[38]:
    {'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'}

    We can verify if an element is in the dictionary:

    In [40]:
    'The Bodyguard' in release_year_dict
    
    Out[40]:
    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 [43]:
    album_sales_dict= { "The Bodyguard":50, "Back in Black":50,"Thriller":65}
    

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

    In [51]:
    album_sales_dict["Thriller"]
    
    Out[51]:
    65

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

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

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

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