University of California San Diego Python Programming Code
Description
Exercise
Dictionaries are one of the fundamental types in Python used to store collections of data. A dictionary uses names which identify the data they hold.
One of the primary reasons for this collection type is that it allows for grouping of related data, much like how data is grouped in the real world. For example, if you wanted to model a person with a dictionary, you could write something like this:
human = {
"first_name": "Paul",
"last_name": "Atreides",
"favorite_food": "spice",
"age": 35
}
Notice there are identifiers for human attributes such as first name, last name, and age.
You can later retrieve an identifier’s value using “bracket notation”:
human_first_name = human["first_name"]
print("The human's first name is", human_first_name)
You can also create or update an identifier’s value using assignment with “bracket notation”:
human["fear"] = None
print("The human is afraid of", human["fear"]
- Create a dictionary using the curly brace syntax (
{ ... }
) with the three keys ("first_name"
,"last_name"
, and"hobby"
) with appropriate string values, and assign the dictionary to the variableperson
. - Print the value of the
person
variable. Run the script and confirm that the printed dictionary displays all three key-value pairs at once. - Using square bracket notation (
[ ... ]
), get the value stored under the"first_name"
key of the dictionary stored in theperson
variable and assign it to the variablefirst_name
. - Using the
get()
method, get the value stored under the"last_name"
key of the dictionary stored in theperson
variable and assign it to the variablelast_name
. - Using the
get()
method, attempt to get the value stored under the"middle_name"
key (which doesn’t exist, but try it anyway) of the dictionary stored in theperson
variable and assign it to the variablemiddle_name
. - In a single
print
statement, print the values of thefirst_name
,middle_name
, andlast_name
variables. Write down the full name you expect to print out, then run the script and examine the terminal’s output. Did the names print out like you expected? - Using square bracket notation, add a new key named
"job"
to the dictionary stored in theperson
variable and give it an appropriate string value. - Print the value under the
"job"
key in theperson
dictionary. - Using square bracket notation, update the value under the
"hobby"
key to a different string value. - Print the value under the
"hobby"
key. - Using the
pop()
method, remove the"last_name"
key from the dictionary stored in theperson
variable. - Print dictionary in the
person
variable. Run the script and verify the output contains the"first_name"
,"hobby"
, and"job"
keys; but does not contain the"last_name"
key.
Have a similar assignment? "Place an order for your assignment and have exceptional work written by our team of experts, guaranteeing you A results."