10.3: Dictionary Operations
- Page ID
- 117587
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\dsum}{\displaystyle\sum\limits} \)
\( \newcommand{\dint}{\displaystyle\int\limits} \)
\( \newcommand{\dlim}{\displaystyle\lim\limits} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\(\newcommand{\longvect}{\overrightarrow}\)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)By the end of this section you should be able to
- Recognize that a dictionary object is mutable.
- Evaluate dictionary items, keys, and values.
- Demonstrate the ability to access, evaluate, and modify dictionary items.
- Modify a dictionary by adding items.
- Modify a dictionary by removing items.
Accessing dictionary items
In Python, values associated with keys in a dictionary can be accessed using the keys as indexes. Here are two ways to access dictionary items in Python:
- Square bracket notation: Square brackets
[]with the key inside access the value associated with that key. If the key is not found, an exception will be thrown. get()method: Theget()method is called with the key as an argument to access the value associated with that key. If the key is not found, the method returnsNoneby default, or a default value specified as the second argument.
Ex: In the code below, a dictionary object my_dict is initialized with items {"apple": 2, "banana": 3, "orange": 4}. The square bracket notation and get() method are used to access values associated with the keys "banana" and "apple", respectively. When accessing the dictionary to obtain the key "pineapple", -1 is returned since the key does not exist in the dictionary.
my_dict = {"apple": 2, "banana": 3, "orange": 4}
print(my_dict["banana"]) # Prints: 3
print(my_dict.get("apple")) # Prints: 2
print(my_dict.get("pineapple", -1)) # Prints: -1
Given the dictionary members = {"Jaya": "Student", "John": "TA", "Ksenia": "Staff"}, answer the following questions.
What is the output of members["Jaya"]?
0None"Student
- Answer
-
c. The value associated with the key
"Jaya"is"Student".
What is the output of members.get("jaya")?
0None"Student"
- Answer
-
b. When a key does not exist in a dictionary,
Noneis returned by default.
What is the output of members.get("jaya", "does not exist")?
"Student""does not exist"None
- Answer
-
b. The second argument to the
get()function will be returned if the key is not found in the dictionary.
Obtaining dictionary keys and values
Dictionary keys, values, and both keys and values can be obtained using keys(), values(), and items() function calls, respectively. The return type of keys(), values(), and items() are dict_keys, dict_values, and dict_items, which can be converted to a list object using the list constructor list().
A dictionary object with items {"a": 97, "b": 98, "c": 99} is created. Functions keys(), values(), and items() are called to obtain keys, values, and items in the dictionary, respectively. list() is also used to convert the output to a list object.
dictionary_object = {"a": 97, "b": 98, "c": 99}
print(dictionary_object.keys())
print(list(dictionary_object.keys()))
print(dictionary_object.values())
print(dictionary_object.items())
The above code's output is:
dict_keys(["a", "b", "c"])
["a", "b", "c"]
dict_values([97, 98, 99])
dict_items([("a", 97), ("b", 98), ("c", 99)])
Given the dictionary numbers = {"one": 1, "two": 2, "three": 3}, answer the following questions.4.
What is the output type of numbers.keys()?
dict_keysdict_valueslist
- Answer
-
a. The return type of
keys()function isdict_keys.
What is the output of print(numbers.values())?
[1, 2, 3]dict_keys([1, 2, 3])dict_values([1, 2, 3])
- Answer
-
c. The values in the numbers dictionary are
1,2, and3. When printingnumbers.values(),dict_values([1, 2, 3])is printed.
What is the output of print(list(numbers.keys()))?
["three", "two", "one"]["one", "two", "three"]dict_keys(["one", "two", "three"])
- Answer
-
b. Keys in the dictionary are
"one", "two", "three". Using thelist()constructor, a list object containing all keys is returned.
Dictionary mutability
In Python, a dictionary is a mutable data type, which means that a dictionary's content can be modified after creation. Dictionary items can be added, updated, or deleted from a dictionary after a dictionary object is created.
To add an item to a dictionary, either the square bracket notation or update() function can be used.
- Square bracket notation: When using square brackets to create a new key object and assign a value to the key, the new key-value pair will be added to the dictionary.
my_dict = {"apple": 2, "banana": 3, "orange": 4} my_dict["pineapple"] = 1 print(my_dict) # Prints: {"apple": 2, "banana": 3, "orange": 4, "pineapple": 1} update()method: theupdate()method can be called with additional key-value pairs to update the dictionary content.my_dict = {"apple": 2, "banana": 3, "orange": 4} my_dict.update({"pineapple": 1, "cherry": 0}) print(my_dict) # Prints: {"apple": 2, "banana": 3, "orange": 4, "pineapple": 1, "cherry": 0}
To modify a dictionary item, the two approaches above can be used on an existing dictionary key along with the updated value. Ex:
- Square bracket notation:
my_dict = {"apple": 2, "banana": 3, "orange": 4} my_dict["apple"] = 1 print(my_dict) # Prints: {"apple": 1, "banana": 3, "orange": 4} update()method:my_dict = {"apple": 2, "banana": 3, "orange": 4} my_dict.update({"apple": 1}) print(my_dict) # Prints: {"apple": 1, "banana": 3, "orange": 4}
Items can be deleted from a dictionary using the del keyword or the pop() method.
delkeyword:my_dict = {"apple": 2, "banana": 3, "orange": 4} del my_dict["orange"] print(my_dict) # Prints: {"apple": 2, "banana": 3}pop()method:my_dict = {"apple": 2, "banana": 3, "orange": 4} deleted_value = my_dict.pop("banana") print(deleted_value) # Prints: 3 print(my_dict) # Output: {"apple": 2, "orange": 4}
Given the dictionary food = {"Coconut soup": "$15", "Butter Chicken": "$18", "Kabob": "$20"}, answer the following questions.7.
Which option modifies the value for the key "Coconut soup" to "$11" while keeping other items the same?
food = {""Coconut soup": "$15""}food["Coconut soup"] = 11food["Coconut soup"] = "$11"
- Answer
-
c. When accessing a dictionary key and assigning a new value, the associated value for the key will be updated.
Which option removes the item "Butter Chicken": "$18" from the food dictionary?
food.remove("Butter Chicken")del food["Butter Chicken"]del food.del("Butter Chicken")
- Answer
-
b. Using the
delkeyword, items can be deleted from a dictionary using the key.
What is the content of the food dictionary after calling food.update({"Kabob": "$22", "Sushi": "$16"})?
{"Coconut soup": "$15", "Butter Chicken": "$18", "Kabob": "$22", "Sushi": "$16"}{"Coconut soup": "$15", "Butter Chicken": "$18", "Kabob": "$20", "Sushi": "$16"}{ "Sushi": "$16", "Coconut soup": "$15", "Butter Chicken": "$18", "Kabob": "$20"}
- Answer
-
a. The
update()function modifies the value associated with the key"Kabob"and adds a new item,"Sushi": "$16".
Follow the steps below to create a dictionary of cars and modify it step-by-step.
- Create an empty dictionary.
- Add a key-value pair of
"Mustang": 10. - Add another key-value pair of
"Volt": 3. - Print the dictionary.
- Modify the value associated with key
"Mustang"to be equal to2. - Delete key
"Volt"and the associated value. - Print the dictionary content.
Prints {"Mustang": 2}
Interactive Code
- Answer
-
# 1. Create an empty dictionary.
my_dict = {}
# 2. Add a key-value pair of "Mustang": 10.
my_dict["Mustang"] = 10
# 3. Add another key-value pair of "Volt": 3.
my_dict["Volt"] = 3
# 4 Print the dictionary
print(my_dict)
# 5. Modify the value associated with key "Mustang" to be equal to 2.
my_dict.update({"Mustang": 2})
# 6. Delete key "Volt" and the associated value.
del my_dict["Volt"]
# 7. Print the dictionary
print(my_dict)
Given a string value, calculate and print the number of unique characters using a dictionary.
Input:
string_value = "This is a string"
Prints 10
Interactive Code
- Answer
-
string_value = "This is a string"
characters = {}for c in string_value:
characters[c] = 1print(len(list(characters.keys())))


