Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Created on Skills Network Labs
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<center>\n",
" <img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/IDSNlogo.png\" width=\"300\" alt=\"cognitiveclass.ai logo\" />\n",
"</center>\n",
"\n",
"# Dictionaries in Python\n",
"\n",
"Estimated time needed: **20** minutes\n",
"\n",
"## Objectives\n",
"\n",
"After completing this lab you will be able to:\n",
"\n",
"- Work with libraries in Python, including operations\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2>Table of Contents</h2>\n",
"<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n",
" <ul>\n",
" <li>\n",
" <a href=\"#dic\">Dictionaries</a>\n",
" <ul>\n",
" <li><a href=\"content\">What are Dictionaries?</a></li>\n",
" <li><a href=\"key\">Keys</a></li>\n",
" </ul>\n",
" </li>\n",
" <li>\n",
" <a href=\"#quiz\">Quiz on Dictionaries</a>\n",
" </li>\n",
" </ul>\n",
"\n",
"</div>\n",
"\n",
"<hr>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"Dic\">Dictionaries</h2>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h3 id=\"content\">What are Dictionaries?</h3>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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 the keys that are used to access values within a dictionary.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/DictsList.png\" width=\"650\" />\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"An example of a Dictionary <code>Dict</code>:\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"{'key1': 1,\n",
" 'key2': '2',\n",
" 'key3': [3, 3, 3],\n",
" 'key4': (4, 4, 4),\n",
" 'key5': 5,\n",
" (0, 1): 6}"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Create the dictionary\n",
"\n",
"Dict = {\"key1\": 1, \"key2\": \"2\", \"key3\": [3, 3, 3], \"key4\": (4, 4, 4), ('key5'): 5, (0, 1): 6}\n",
"Dict"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The keys can be strings:\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Access to the value by the key\n",
"\n",
"Dict[\"key1\"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Keys can also be any immutable object such as a tuple: \n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"6"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Access to the value by the key\n",
"\n",
"Dict[(0, 1)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Each key is separated from its value by a colon \"<code>:</code>\". 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 \"<code>{}</code>\".\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"{'Thriller': '1982',\n",
" 'Back in Black': '1980',\n",
" 'The Dark Side of the Moon': '1973',\n",
" 'The Bodyguard': '1992',\n",
" 'Bat Out of Hell': '1977',\n",
" 'Their Greatest Hits (1971-1975)': '1976',\n",
" 'Saturday Night Fever': '1977',\n",
" 'Rumours': '1977'}"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Create a sample dictionary\n",
"\n",
"release_year_dict = {\"Thriller\": \"1982\", \"Back in Black\": \"1980\", \\\n",
" \"The Dark Side of the Moon\": \"1973\", \"The Bodyguard\": \"1992\", \\\n",
" \"Bat Out of Hell\": \"1977\", \"Their Greatest Hits (1971-1975)\": \"1976\", \\\n",
" \"Saturday Night Fever\": \"1977\", \"Rumours\": \"1977\"}\n",
"release_year_dict"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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 one 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.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is helpful to visualize the dictionary as a table, as in the following image. The first column represents the keys, the second column represents the values.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/DictsStructure.png\" width=\"650\" />\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h3 id=\"key\">Keys</h3>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can retrieve the values based on the names:\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"'1982'"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get value by keys\n",
"\n",
"release_year_dict['Thriller'] "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This corresponds to: \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/DictsKeyOne.png\" width=\"500\" />\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Similarly for <b>The Bodyguard</b>\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"'1992'"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get value by key\n",
"\n",
"release_year_dict['The Bodyguard'] "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/DictsKeyTwo.png\" width=\"500\" />\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let us retrieve the keys of the dictionary using the method <code>keys()</code>:\n"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"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'])"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get all the keys in dictionary\n",
"\n",
"release_year_dict.keys()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can retrieve the values using the method <code>values()</code>:\n"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"dict_values(['1982', '1980', '1973', '1992', '1977', '1976', '1977', '1977'])"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get all the values in dictionary\n",
"\n",
"release_year_dict.values() "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can add an entry:\n"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"{'Thriller': '1982',\n",
" 'Back in Black': '1980',\n",
" 'The Dark Side of the Moon': '1973',\n",
" 'The Bodyguard': '1992',\n",
" 'Bat Out of Hell': '1977',\n",
" 'Their Greatest Hits (1971-1975)': '1976',\n",
" 'Saturday Night Fever': '1977',\n",
" 'Rumours': '1977',\n",
" 'Graduation': '2007'}"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Append value with key into dictionary\n",
"\n",
"release_year_dict['Graduation'] = '2007'\n",
"release_year_dict"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can delete an entry: \n"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"{'Back in Black': '1980',\n",
" 'The Dark Side of the Moon': '1973',\n",
" 'The Bodyguard': '1992',\n",
" 'Bat Out of Hell': '1977',\n",
" 'Their Greatest Hits (1971-1975)': '1976',\n",
" 'Saturday Night Fever': '1977',\n",
" 'Rumours': '1977'}"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Delete entries by key\n",
"\n",
"del(release_year_dict['Thriller'])\n",
"del(release_year_dict['Graduation'])\n",
"release_year_dict"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" We can verify if an element is in the dictionary: \n"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Verify the key is in the dictionary\n",
"\n",
"'The Bodyguard' in release_year_dict"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"quiz\">Quiz on Dictionaries</h2>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<b>You will need this dictionary for the next two questions:</b>\n"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'The Bodyguard': '1992', 'Saturday Night Fever': '1977'}"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Question sample dictionary\n",
"\n",
"soundtrack_dic = {\"The Bodyguard\":\"1992\", \"Saturday Night Fever\":\"1977\"}\n",
"soundtrack_dic "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"a) In the dictionary <code>soundtrack_dic</code> what are the keys ?\n"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"dict_keys(['The Bodyguard', 'Saturday Night Fever'])"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Write your code below and press Shift+Enter to execute\n",
"soundtrack_dic.keys()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python\n",
"soundtrack_dic.keys() # The Keys \"The Bodyguard\" and \"Saturday Night Fever\" \n",
"\n",
"```\n",
"\n",
"</details>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"b) In the dictionary <code>soundtrack_dic</code> what are the values ?\n"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"dict_values(['1992', '1977'])"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Write your code below and press Shift+Enter to execute\n",
"soundtrack_dic.values()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python\n",
"soundtrack_dic.values() # The values are \"1992\" and \"1977\"\n",
"\n",
"```\n",
"\n",
"</details>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<b>You will need this dictionary for the following questions:</b>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Albums <b>Back in Black</b>, <b>The Bodyguard</b> and <b>Thriller</b> have the following music recording sales in millions 50, 50 and 65 respectively:\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"a) Create a dictionary <code>album_sales_dict</code> where the keys are the album name and the sales in millions are the values. \n"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'Back in Black': 50, 'The Bodyguard': 50, 'Thriller': 65}"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Write your code below and press Shift+Enter to execute\n",
"album_sales_dict = {\"Back in Black\":50, \"The Bodyguard\":50, \"Thriller\":65}\n",
"album_sales_dict"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python\n",
"album_sales_dict = {\"The Bodyguard\":50, \"Back in Black\":50, \"Thriller\":65}\n",
"\n",
"```\n",
"\n",
"</details>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"b) Use the dictionary to find the total sales of <b>Thriller</b>:\n"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"65"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Write your code below and press Shift+Enter to execute\n",
"album_sales_dict[\"Thriller\"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python\n",
"album_sales_dict[\"Thriller\"]\n",
"\n",
"```\n",
"\n",
"</details>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"c) Find the names of the albums from the dictionary using the method <code>keys()</code>:\n"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"dict_keys(['Back in Black', 'The Bodyguard', 'Thriller'])"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Write your code below and press Shift+Enter to execute\n",
"album_sales_dict.keys()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python\n",
"album_sales_dict.keys()\n",
"\n",
"```\n",
"\n",
"</details>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"d) Find the values of the recording sales from the dictionary using the method <code>values</code>:\n"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"dict_values([50, 50, 65])"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Write your code below and press Shift+Enter to execute\n",
"album_sales_dict.values()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python\n",
"album_sales_dict.values()\n",
"\n",
"```\n",
"\n",
"</details>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n",
"<h2>The last exercise!</h2>\n",
"<p>Congratulations, you have completed your first lesson and hands-on lab in Python. However, there is one more thing you need to do. The Data Science community encourages sharing work. The best way to share and showcase your work is to share it on GitHub. By sharing your notebook on GitHub you are not only building your reputation with fellow data scientists, but you can also show it off when applying for a job. Even though this was your first piece of work, it is never too early to start building good habits. So, please read and follow <a href=\"https://cognitiveclass.ai/blog/data-scientists-stand-out-by-sharing-your-notebooks/\" target=\"_blank\">this article</a> to learn how to share your work.\n",
"<hr>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Author\n",
"\n",
"<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\" target=\"_blank\">Joseph Santarcangelo</a>\n",
"\n",
"## Other contributors\n",
"\n",
"<a href=\"www.linkedin.com/in/jiahui-mavis-zhou-a4537814a\">Mavis Zhou</a>\n",
"\n",
"## Change Log\n",
"\n",
"| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n",
"| ----------------- | ------- | ------------- | ------------------------------------------------------------------- |\n",
"| 2020-09-09 | 2.1 | Malika Singla | Updated the variable soundtrack_dict to soundtrack_dic in Questions |\n",
"| 2020-08-26 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n",
"| | | | |\n",
"| | | | |\n",
"\n",
"## <h3 align=\"center\"> © IBM Corporation 2020. All rights reserved. <h3/>\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python",
"language": "python",
"name": "conda-env-python-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.13"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment