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.
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]:
The keys can be strings:
In [2]:
Dict["key1"]
Out[2]:
Keys can also be any immutable object such as a tuple:
In [3]:
Dict[(0,1)]
Out[3]:
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]:
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.
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]:
In [6]:
soundtrack_dic.keys()
Out[6]:
You can retrieve the values based on the names:
In [7]:
release_year_dict['Thriller']
Out[7]:
This corresponds to:
Similarly for The Bodyguard
In [8]:
release_year_dict['The Bodyguard']
Out[8]:
Now let us retrieve the keys of the dictionary using the method release_year_dict():
In [9]:
release_year_dict.keys()
Out[9]:
You can retrieve the values using the method values()
:
In [10]:
release_year_dict.values()
Out[10]:
We can add an entry:
In [11]:
release_year_dict['Graduation']='2007'
release_year_dict
Out[11]:
We can delete an entry:
In [12]:
del(release_year_dict['Thriller'])
del(release_year_dict['Graduation'])
release_year_dict
Out[12]:
We can verify if an element is in the dictionary:
In [13]:
'The Bodyguard' in release_year_dict
Out[13]:
In [15]:
album_sales_dict = {'Back in Black':50, 'The Bodygaurd':50, 'Thriller':65}
In [16]:
album_sales_dict['Thriller']
Out[16]:
In [17]:
album_sales_dict.keys()
Out[17]:
In [18]:
album_sales_dict.values()
Out[18]:
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.