{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Dictionaries and their usage\n",
"In this lecture, we discuss a more advance data structure, *dictionary*, in Python.
\n",
"The **key concept** in using dictionary is that each item in a distionary is a ** pair.
\n",
"Another important thing to remember is that dictionary **does not** store these key values paris in any paritcular order.\n",
"\n",
"**Created and edited by:** John C.S. Lui, August 9th, 2020.\n",
"\n",
"**Important note**: If you want to use and modify this notebook file, please acknowledge the author."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## General Syntax of dictionary\n",
"\n",
"dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}\n",
"\n",
"Let illustrate it using an example."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Define a disctionary which stores professor's name and his/her research interests\n",
"\n",
"professors_interests = {\n",
" 'john c. s. lui': [ 'applied machine learning', 'network science', 'network economics', 'mobile and IoT security'],\n",
" 'patrick p. c. lee': ['file and storage systems', 'network monitoring' ],\n",
" 'james cheng': ['distributed systems', 'big data analytic systems', 'distributed machine learning systems']\n",
" }\n",
"\n",
"print(professors_interests)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Let see how we can access items in the disctionary\n",
"\n",
"# Accessing dictionary via keys\n",
"print(\"For %s, research interests are: %s\" %('john c. s. lui'.title(), professors_interests['john c. s. lui'])) \n",
"print(\"For %s, research interests are: %s\" %('patrick p. c. lee'.title(), professors_interests['patrick p. c. lee'])) \n",
"print(\"For %s, research interests are: %s\" %('james cheng'.title(), professors_interests['james cheng']))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Define a disctionary which stores professor's name and his/her research interests\n",
"\n",
"professors_interests = {\n",
" 'john c. s. lui': [ 'applied machine learning', 'network science', 'network economics', 'mobile and IoT security'],\n",
" 'patrick p. c. lee': ['file and storage systems', 'network monitoring' ],\n",
" 'james cheng': ['distributed systems', 'big data analytic systems', 'distributed machine learning systems']\n",
" }\n",
"\n",
"# Let's access items within the research interests\n",
"name = ''\n",
"name = input('Please input name: ') # Ask user to enter the name (or key)\n",
"\n",
"while name != 'q':\n",
" if name in professors_interests: # check whether the \"key\" is in the disctionary !!!!\n",
" print(\"For %s, research interests are: \" %name.title())\n",
" interests = professors_interests[name] # given the key name, access value (or the list)\n",
" for item in interests: # access each item within a list\n",
" print(\"\\t\" + str(interests.index(item)+1) + \". \" + item.title())\n",
" else:\n",
" print(\"Sorry, the name is not in the list.\")\n",
" \n",
" name = input('Please input name: ') # ask user to input again"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Let see how we can loop through all elements in the dictionary\n",
"# Define a disctionary which stores professor's name and his/her research interests\n",
"\n",
"professors_interests = {\n",
" 'john c. s. lui': [ 'applied machine learning', 'network science', 'network economics', 'mobile and IoT security'],\n",
" 'patrick p. c. lee': ['file and storage systems', 'network monitoring' ],\n",
" 'james cheng': ['distributed systems', 'big data analytic systems', 'distributed machine learning systems']\n",
" }\n",
"\n",
"for name, interests in professors_interests.items(): # extract the key:value of each item in the dictionary\n",
" print(\"For Professor \" + name.title() + \", interests are: \", end='')\n",
" for interest in interests:\n",
" if interest != interests[-1]:\n",
" print(interest +\", \", end='')\n",
" else:\n",
" print(interest +\".\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Some common functions for dictionary\n",
"Let's illustrate some useful dictionary functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Create a new and empty dictionary\n",
"professors = {}\n",
"\n",
"# Fill it with some key:value pairs\n",
"# In here, key is the name (string) of a professor\n",
"# value is a list, which contains research interests (list), rank (string) and age (integer)\n",
"professors['john c. s. lui'] =[['applied machine learning', 'network science', 'network economics', 'mobile and IoT security'], \n",
" 'stupid professor', 82] \n",
"professors['patrick p. c. lee'] = [['file and storage systems', 'network monitoring'], 'associate professor', 25]\n",
"professors['james cheng'] = [['distributed systems', 'big data analytic systems', 'distributed machine learning systems'],\n",
" 'associate professor', 18]\n",
"professors['eric lo'] = [['block chain', 'database systems', 'big data computing'], 'associate professor', 19]\n",
"\n",
"# Display them out\n",
"for name, a_list in professors.items():\n",
" research_interest = a_list[0] # get research interest\n",
" rank = a_list[1] # get rank\n",
" age = a_list[2] # get age\n",
" print(\"\\nName: \" + name.title() + \", age = \" + str(age) + \", rank = \" + rank.title() + \".\")\n",
" print(\" \"+\"Research interests are: \", end='')\n",
" for research_area in research_interest:\n",
" if research_area != research_interest[-1]:\n",
" print(research_area + \", \", end='')\n",
" else:\n",
" print(research_area + \".\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## How can we modify the values?\n",
"Let say some professors have some new research interests, or need to delete some old interest. What can we do?
\n",
"Let's illustrate."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Create a new and empty dictionary\n",
"professors = {}\n",
"\n",
"# Fill it with some key:value pairs\n",
"# In here, key is the name (string) of a professor\n",
"# value is a list, which contains research interests (list), rank (string) and age (integer)\n",
"professors['john c. s. lui'] =[['applied machine learning', 'network science', 'network economics', 'mobile and IoT security'], \n",
" 'full professor', 82] \n",
"professors['patrick p. c. lee'] = [['file and storage systems', 'network monitoring'], 'associate professor', 25]\n",
"professors['james cheng'] = [['distributed systems', 'big data analytic systems', 'distributed machine learning systems'],\n",
" 'assistant professor', 18]\n",
"professors['eric lo'] = [['block chain', 'database systems', 'big data computing'], 'associate professor', 19]\n",
"\n",
"\n",
"# Let say all professors have a new research interests of \"A.I.\"\n",
"for name, a_list in professors.items():\n",
" a_list[0].append('A.I.') # adding a new research topic to all professors in the dictionary\n",
" research_interest = a_list[0] # get research interest\n",
" rank = a_list[1] # get rank\n",
" age = a_list[2] # get age\n",
" print(\"\\nName: \" + name.title() + \", age = \" + str(age) + \", rank = \" + rank.title() + \".\")\n",
" print(\" \"+\"Research interests are: \", end='')\n",
" for research_area in research_interest:\n",
" if research_area != research_interest[-1]:\n",
" print(research_area + \", \", end='')\n",
" else:\n",
" print(research_area + \".\")\n",
" \n",
"print('\\n------------------------------\\n')\n",
"\n",
"# Let say that AI is not hot anymore, and 'john c. s. lui' wants to drop it from his research interests.\n",
"professors['john c. s. lui'][0].remove('A.I.') # access the value with index 0 being list of research interests\n",
"print( professors['john c. s. lui'][0]) # print out the research interest of john c. s. lui"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## How can we modify keys?\n",
"To modify keys, it is a bit more complicated. Let's illustrate.\n",
"\n",
"Assume we want to change \"john c. s. lui\" to \"John C.S. Lui\" (or changing the key)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Create a dictionary\n",
"professors = {}\n",
"professors['john c. s. lui'] =[['applied machine learning', 'network science', 'network economics', 'mobile and IoT security'], \n",
" 'full professor', 82] \n",
"professors['patrick p. c. lee'] = [['file and storage systems', 'network monitoring'], 'associate professor', 25]\n",
"professors['james cheng'] = [['distributed systems', 'big data analytic systems', 'distributed machine learning systems'],\n",
" 'assistant professor', 18]\n",
"professors['eric lo'] = [['block chain', 'database systems', 'big data computing'], 'associate professor', 19]\n",
"\n",
"# Let's copy the \"value\" of the key 'john c. s. lui' to a new key 'John C.S. Lui'. Then delete the old key:value pair.\n",
"\n",
"professors['John C.S. Lui'] = professors['john c. s. lui'] # create a new key:value pair\n",
"del professors['john c. s. lui']\n",
"\n",
"# Let's print out the dictionary\n",
"for name, a_list in professors.items():\n",
" a_list[0].append('A.I') # adding a new research topic to all professors in the dictionary\n",
" research_interest = a_list[0] # get research interest\n",
" rank = a_list[1] # get rank\n",
" age = a_list[2] # get age\n",
" print(\"\\nName: \" + name.title() + \", age = \" + str(age) + \", rank = \" + rank.title() + \".\")\n",
" print(\" \"+\"Research interests are: \", end='')\n",
" for research_area in research_interest:\n",
" if research_area != research_interest[-1]:\n",
" print(research_area + \", \", end='')\n",
" else:\n",
" print(research_area + \".\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Looping through all items in a dictionary\n",
"We have seen this before. But let's use a \"simple\" example.
\n",
"The **main idea** is to use `items()` so to obtain **all key-value pairs** from a dictionary into a **list**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"my_dictionary = {'key1':'key1_value', 'key2': 'key2_value', 'key3':'key3_value', 'key4':'key4_value'}\n",
"\n",
"for key, value in my_dictionary.items():\n",
" print('k:v pair is ' + key + \" \" + value)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Looping through all keys in a dictionary\n",
"The **main idea** is to use `keys()` to get all keys from a disctionary into a **list**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"my_dictionary = {'key1':'key1_value', 'key2': 'key2_value', 'key3':'key3_value', 'key4':'key4_value'}\n",
"\n",
"for key in my_dictionary.keys():\n",
" print(key)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is actually the **default behavior** of looping through the dictionary itself.
\n",
"So you can leave out the `.keys()` part, and get the exact same behavior:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"my_dictionary = {'key1':'key1_value', 'key2': 'key2_value', 'key3':'key3_value', 'key4':'key4_value'}\n",
"\n",
"for key in my_dictionary:\n",
" print('for key='+ key +', its value is ' + my_dictionary[key])\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Let's consider more examples\n",
"subjects = {'computer science': 'A study of the science and technology of computing.',\n",
" 'medicine': 'A study of biology, disease and its cure.',\n",
" 'BBA': 'A study of,... well, it is not a serious subject :-) .'\n",
" }\n",
"\n",
"# Show each subject in our dictionary.\n",
"print(\"The following subjects are in our dictionary:\")\n",
"for subject in subjects:\n",
" print(\"- %s\" % subject)\n",
" \n",
"# Allow the user to type in a word, and then display the meaning for that word.\n",
"requested_subject = input(\"\\nWhat subject you are looking for? \")\n",
"if requested_subject in subjects.keys():\n",
" print(\"\\n%s: %s\" % (requested_subject, subjects[requested_subject]))\n",
"else:\n",
" print (\"\\nThe requested subject is NOT in the dictionary\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Let's modify the above program so that user can keep asking information\n",
"\n",
"subjects = {'computer science': 'A study of the science and technology of computing.',\n",
" 'medicine': 'A study of biology, disease and its cure.',\n",
" 'BBA': 'A study of,... well, not a serious subject :-) .'\n",
" }\n",
"\n",
"# Show each subject in our dictionary.\n",
"print(\"The following subjects are in our dictionary:\")\n",
"for subject in subjects:\n",
" print(\"- %s\" % subject)\n",
" \n",
"# Allow the user to type in a word, and then display the meaning for that word.\n",
"requested_subject = input(\"\\nWhat subject you are looking for? \") # ask input from user\n",
"while requested_subject != 'quit':\n",
" if requested_subject in subjects.keys():\n",
" print(\"\\n%s: %s\" % (requested_subject, subjects[requested_subject]))\n",
" else:\n",
" print (\"\\nThe requested subject is NOT in the dictionary\")\n",
" requested_subject = input(\"\\nWhat subject you are looking for? \") # ask input from user\n",
"print('You have selected to quit.')\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Looping through all values in a dictionary\n",
"The **main idea** is to use `values()` to get all keys from a disctionary into a **list**\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# define a dictionary\n",
"\n",
"subjects = {'computer science': 'A study of the science and technology of computing.',\n",
" 'medicine': 'A study of biology, disease and its cure.',\n",
" 'economics': 'A study of the production, consumption, and transfer of wealth.',\n",
" 'theology': 'A study of the nature of God and religious belief.',\n",
" 'BBA': 'A study of,... well, not a serious subject :-) .'\n",
" }\n",
"\n",
"for value in subjects.values():\n",
" print('values are:', value)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Let's process each word in each of the value\n",
"\n",
"# define a dictionary\n",
"subjects = {'computer science': 'A study of the science and technology of computing.',\n",
" 'medicine': 'A study of biology, disease and its cure.',\n",
" 'economics': 'A study of the production, consumption, and transfer of wealth.',\n",
" 'theology': 'A study of the nature of God and religious belief.',\n",
" 'BBA': 'A study of,... well, not a serious subject :-) .'\n",
" }\n",
"for value in subjects.values(): # access the sting in each value\n",
" words_in_value = value.split( ) # separate each word in the string via the 'space' separator (now we have a list)\n",
" print(\"\\nFor VALUE:\", words_in_value, \", \", \"\\neach words are:\")\n",
" for word in words_in_value:\n",
" print(word + \", \", end='')\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Let's write a program to allow user to \"search\" for keyword in each value\n",
"\n",
"# define a dictionary\n",
"subjects = {'computer science': 'A study of the science and technology of computing.',\n",
" 'medicine': 'A study of biology, disease and its cure.',\n",
" 'economics': 'A study of the production, consumption, and transfer of wealth.',\n",
" 'theology': 'A study of the nature of God and religious belief.',\n",
" 'BBA': 'A study of,... well, not a serious subject :-) .'\n",
" }\n",
"\n",
"\n",
"# Ask user to input keyword to search\n",
"keyword = input(\"\\nPlease type in a keyword: \") # ask input from user\n",
"\n",
"while keyword.upper() != 'QUIT': # convert string to upper case\n",
" found_flag = False\n",
" for key, value in subjects.items(): # loop through all key/value pair\n",
" value = value.replace(',', ' ') # replace all comma and period so as to facilitate search\n",
" value = value.replace('.', ' ')\n",
" words_in_value = value.split() # get a list of words in the value\n",
" # print(words_in_value)\n",
" if keyword in words_in_value:\n",
" print(\"The subject you are looking for is \", key)\n",
" found_flag = True\n",
"\n",
" if found_flag == False:\n",
" print(\"Can't find the keyword in the dictionary\")\n",
" keyword = input(\"\\nPlease type in a keyword: \") "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## How can we \"add\" items in a dictionary?\n",
"Let's illustrate"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# define a dictionary\n",
"subjects = {'computer science': 'A study of the science and technology of computing.',\n",
" 'medicine': 'A study of biology, disease and its cure.',\n",
" 'economics': 'A study of the production, consumption, and transfer of wealth.',\n",
" 'theology': 'A study of the nature of God and religious belief.',\n",
" 'BBA': 'A study of,... well, well, not a serious subject :-) .'\n",
" }\n",
"\n",
"subjects['chemistry'] = 'A study of the properties and characteristics of substances.'\n",
"subjects['philosophy'] = 'A study of the fundamental nature of knowledge, reality, and existence.'\n",
"for key, value in subjects.items():\n",
" print('Key = ' + key +', value = ' + value )\n",
" \n",
"print('\\nEasy as a pie !!!')\n",
"\n",
"print (\"Note that things may NOT be stored in our expected order\") # Illustrate the storage ordering\n",
"subjects"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Lists in a dictionary\n",
"In dictionary, the key and value do not need to be of the same type. Let's consider a list as value"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# define a score sheet for all students. Note that the lists DON'T have to have the same dimension !!!\n",
"score_sheet = {'john': [100, 100, 100, 100, 100],\n",
" 'peter': [99, 99, 99],\n",
" 'jack': [50,0, 50, 0]}\n",
"\n",
"# Display their scores\n",
"print('For John, his scores are:', score_sheet['john'])\n",
"print('For Peter, his scores are:', score_sheet['peter'])\n",
"print('For Jack, his scores are:', score_sheet['jack'])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Let's put these print statements in a loop\n",
"# define a score sheet for all students\n",
"score_sheet = {'john': [100, 100, 100, 100, 100],\n",
" 'peter': [99, 99, 99],\n",
" 'jack': [50,0, 50, 0]}\n",
"\n",
"# Display their scores\n",
"#for name in score_sheet.keys(): # Note that this also works !!!!!!\n",
"for name in score_sheet:\n",
" print('For ' + name.title() + ', his scores are: ', score_sheet[name])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Let's access each number within the list\n",
"# define a score sheet for all students\n",
"score_sheet = {'john': [100, 100, 100, 100, 100],\n",
" 'peter': [99, 99, 99],\n",
" 'jack': [50,0, 50, 0]}\n",
"\n",
"# Display their scores\n",
"#for name in score_sheet.keys(): # Note that this also works !!!!!!\n",
"for name in score_sheet:\n",
" print ('For ' + name.title() + ', his scores are: ', end='')\n",
" for score in score_sheet[name]:\n",
" print(str(score) + ', ', end='')\n",
" print(\"\\n\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise\n",
"Modify the above program so that you can remove the annoyming \",\" and replace it with \".\"."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Dictionaries inside a dictionary\n",
"Let's consider how to nest a dictionary inside of a dictionary."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# This program stores information about pets. For each pet,\n",
"# we store the kind of animal, the owner's name, and\n",
"# the breed.\n",
"pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True},\n",
" 'walter': {'kind': 'cockroach', 'owner': 'jake', 'vaccinated': False},\n",
" 'peso': {'kind': 'dog', 'owner': 'mary', 'vaccinated': True},\n",
" 'john': {'kind': 'dog', 'owner': 'cuhk', 'vaccinated': False}\n",
" }\n",
"\n",
"# Let's show all the information for each pet.\n",
"print(\"Here is what I know about Willie:\")\n",
"print(\"kind: \" + pets['willie']['kind'])\n",
"print(\"owner: \" + pets['willie']['owner'])\n",
"print(\"vaccinated: \" + str(pets['willie']['vaccinated']))\n",
"\n",
"print(\"\\nHere is what I know about Walter:\")\n",
"print(\"kind: \" + pets['walter']['kind'])\n",
"print(\"owner: \" + pets['walter']['owner'])\n",
"print(\"vaccinated: \" + str(pets['walter']['vaccinated']))\n",
"\n",
"print(\"\\nHere is what I know about Peso:\")\n",
"print(\"kind: \" + pets['peso']['kind'])\n",
"print(\"owner: \" + pets['peso']['owner'])\n",
"print(\"vaccinated: \" + str(pets['peso']['vaccinated']))\n",
"\n",
"print(\"\\nHere is what I know about John:\")\n",
"print(\"kind: \" + pets['john']['kind'])\n",
"print(\"owner: \" + pets['john']['owner'])\n",
"print(\"vaccinated: \" + str(pets['john']['vaccinated']))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Let's make the above code conscise.\n",
"pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True},\n",
" 'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False},\n",
" 'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True},\n",
" 'john': {'kind': 'dog', 'owner': 'cuhk', 'vaccinated': False}\n",
" }\n",
"\n",
"# Let's show all the information for each pet.\n",
"for pet_name, pet_information in pets.items():\n",
" print(\"\\nHere is what I know about %s:\" % pet_name.title())\n",
" print(\"kind: \" + pet_information['kind'])\n",
" print(\"owner: \" + pet_information['owner'])\n",
" print(\"vaccinated: \" + str(pet_information['vaccinated']))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The above code won't work if we add more key/value into the dictionary (or the values of pets). \n",
"# Let's modify our code.\n",
"\n",
"pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True},\n",
" 'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False},\n",
" 'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True},\n",
" 'john': {'kind': 'dog', 'owner': 'cuhk', 'vaccinated': False}\n",
" }\n",
"\n",
"# Let's show all the information for each pet.\n",
"for pet_name, pet_information in pets.items():\n",
" print(\"\\nHere is what I know about %s:\" % pet_name.title())\n",
" # Each animal's dictionary is in 'information'\n",
" for key in pet_information:\n",
" print(key + \": \" + str(pet_information[key]))\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Some exercises for dictionary"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# What is the output for the following snippet?\n",
"\n",
"dict1 = {\"key1\":1, \"key2\":2}\n",
"dict2 = {\"key2\":2, \"key1\":1}\n",
"print(dict1 == dict2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# What is the output for the following snippet?\n",
"\n",
"sampleDict = { \n",
" \"class\":{ \n",
" \"student\":{ \n",
" \"name\":\"Mike\",\n",
" \"marks\":{ \n",
" \"physics\":70,\n",
" \"history\":80\n",
" }\n",
" }\n",
" }\n",
"}\n",
"\n",
"# how to access the score in history?\n",
"\n",
"print(sampleDict['class']['student']['marks']['history'])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# What is the output for the following snippet?\n",
"\n",
"sampleDict = dict([('first', 1),('second', 2),('third', 3)])\n",
"\n",
"print(sampleDict)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# What is the output for the following snippet?\n",
"\n",
"student = {1: {'name': 'Emma', 'age': '27', 'sex': 'Female'},\n",
" 2: {'name': 'Mike', 'age': '22', 'sex': 'Male'}}\n",
"\n",
"# how to access Emma's age\n",
"student[1]['age']"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# What is the output for the following snippet?\n",
"\n",
"dict1 = {\"name\": \"Mike\", \"salary\": 8000}\n",
"temp = dict1.pop(\"age\")\n",
"print(temp)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# What is the output for the following snippet?\n",
"\n",
"dict1 = {\"name\": \"Mike\", \"salary\": 8000}\n",
"temp = dict1.get(\"age\")\n",
"print(temp)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Which are the correct ways to empty the following dictionary\n",
"\n",
"student = { \n",
" \"name\": \"Emma\", \n",
" \"class\": 9, \n",
" \"marks\": 75 \n",
"}\n",
"\n",
"# del student[0:2]\n",
"# student.clear()\n",
"# del student\n",
"# print(student)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"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.8.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}