Skip to content

Instantly share code, notes, and snippets.

@aderonkeakinyemi
Created April 8, 2019 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aderonkeakinyemi/eed104cedf6d0a7b84d11d5061c32337 to your computer and use it in GitHub Desktop.
Save aderonkeakinyemi/eed104cedf6d0a7b84d11d5061c32337 to your computer and use it in GitHub Desktop.
Created on Cognitive Class Labs
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n",
" <a href=\"http://cocl.us/topNotebooksPython101Coursera\">\n",
" <img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Ad/TopAd.png\" width=\"750\" align=\"center\">\n",
" </a>\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a href=\"https://cognitiveclass.ai/\">\n",
" <img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Ad/CCLog.png\" width=\"200\" align=\"center\">\n",
"</a>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h1>Dictionaries in Python</h1>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<p><strong>Welcome!</strong> This notebook will teach you about the dictionaries in the Python Programming Language. By the end of this lab, you'll know the basics dictionary operations in Python, including what it is, and the operations on it.</p>"
]
},
{
"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",
" <p>\n",
" Estimated time needed: <strong>20 min</strong>\n",
" </p>\n",
"</div>\n",
"\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"Dic\">Dictionaries</h2>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h3 id=\"content\">What are Dictionaries?</h3>"
]
},
{
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%202/Images/DictsList.png\" width=\"650\" />"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"An example of a Dictionary <code>Dict</code>:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": 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": 1,
"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:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 2,
"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: "
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"6"
]
},
"execution_count": 3,
"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>\"."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": 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": 4,
"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."
]
},
{
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%202/Images/DictsStructure.png\" width=\"650\" />"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h3 id=\"key\">Keys</h3>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can retrieve the values based on the names:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'1982'"
]
},
"execution_count": 5,
"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://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%202/Images/DictsKeyOne.png\" width=\"500\" />"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Similarly for <b>The Bodyguard</b>"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'1992'"
]
},
"execution_count": 6,
"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://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%202/Images/DictsKeyTwo.png\" width=\"500\" />"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let you retrieve the keys of the dictionary using the method <code>release_year_dict()</code>:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": 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": 7,
"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>:"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"dict_values(['1982', '1980', '1973', '1992', '1977', '1976', '1977', '1977'])"
]
},
"execution_count": 8,
"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:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": 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": 9,
"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: "
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": 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": 10,
"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: "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Verify the key is in the dictionary\n",
"\n",
"'The Bodyguard' in release_year_dict"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"quiz\">Quiz on Dictionaries</h2>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<b>You will need this dictionary for the next two questions:</b>"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'The Bodyguard': '1992', 'Saturday Night Fever': '1977'}"
]
},
"execution_count": 11,
"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_dict</code> what are the keys ?"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"dict_keys(['The Bodyguard', 'Saturday Night Fever'])"
]
},
"execution_count": 13,
"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": [
"Double-click __here__ for the solution.\n",
"\n",
"<!-- Your answer is below:\n",
"soundtrack_dic.keys() # The Keys \"The Bodyguard\" and \"Saturday Night Fever\" \n",
"-->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"b) In the dictionary <code>soundtrack_dict</code> what are the values ?"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"dict_values(['1992', '1977'])"
]
},
"execution_count": 15,
"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": [
"Double-click __here__ for the solution.\n",
"\n",
"<!-- Your answer is below:\n",
"soundtrack_dic.values() # The values are \"1992\" and \"1977\"\n",
"-->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<b>You will need this dictionary for the following questions:</b>"
]
},
{
"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:"
]
},
{
"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. "
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": true
},
"outputs": [
{
"data": {
"text/plain": [
"{'Back in Black': 50, 'The Bodyguard': 50, 'Thriller': 65}"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Write your code below and press Shift+Enter to execute\n",
"album_sales_dict = {\"Back in Black\":50, \\\n",
" \"The Bodyguard\": 50, \\\n",
" \"Thriller\": 65}\n",
"album_sales_dict"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Double-click __here__ for the solution.\n",
"\n",
"<!-- Your answer is below:\n",
"album_sales_dict = {\"The Bodyguard\":50, \"Back in Black\":50, \"Thriller\":65}\n",
"-->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"b) Use the dictionary to find the total sales of <b>Thriller</b>:"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"65"
]
},
"execution_count": 19,
"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": [
"Double-click __here__ for the solution.\n",
"\n",
"<!-- Your answer is below:\n",
"album_sales_dict[\"Thriller\"]\n",
"-->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"c) Find the names of the albums from the dictionary using the method <code>keys</code>:"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"dict_keys(['Back in Black', 'The Bodyguard', 'Thriller'])"
]
},
"execution_count": 21,
"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": [
"Double-click __here__ for the solution.\n",
"\n",
"<!-- Your answer is below:\n",
"album_sales_dict.keys()\n",
"-->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"d) Find the names of the recording sales from the dictionary using the method <code>values</code>:"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"dict_values([50, 50, 65])"
]
},
"execution_count": 22,
"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": [
"Double-click __here__ for the solution.\n",
"\n",
"<!-- Your answer is below:\n",
"album_sales_dict.values()\n",
"-->"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# check if \"Bodyguard\" if in your dictionary\n",
"\n",
"\"The Bodyguard\" in album_sales_dict"
]
},
{
"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>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n",
"<h2>Get IBM Watson Studio free of charge!</h2>\n",
" <p><a href=\"https://cocl.us/bottemNotebooksPython101Coursera\"><img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Ad/BottomAd.png\" width=\"750\" align=\"center\"></a></p>\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h3>About the Authors:</h3> \n",
"<p><a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\" target=\"_blank\">Joseph Santarcangelo</a> is a Data Scientist at IBM, and holds 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.</p>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Other contributors: <a href=\"www.linkedin.com/in/jiahui-mavis-zhou-a4537814a\">Mavis Zhou</a>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<p>Copyright &copy; 2018 IBM Developer Skills Network. This notebook and its source code are released under the terms of the <a href=\"https://cognitiveclass.ai/mit-license/\">MIT License</a>.</p>"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"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.8"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment