Dictionaries
The built-in Python dictionary class
dict is
an unordered collection of elements, each of which has a unique key and a value. A
key can be any immutable object, but a string is most common. A value
can be any object. The basic syntax to create a dict object
with keys k\(x\) and values v\(x\)
is {k1: v1, k2: v2, ...}. For
instance, we can define a dict as
follows:
d = {"foo": 5, "bar": 1, "baz": -3}Accessing a value requires its key. To access a value in dictionary
d with key k, use the syntax d[k]. For example,
d = { # It is often useful to break lines at each key-value pair
"name": "Spiff",
"age": 33,
"occupation": "spaceman",
"enemies": ["Zorgs", "Zargs", "Zogs"]
}
print(f"{d['name']} is a {d['age']} year old"
f"{d['occupation']} who fights {d['enemies'][0]}.")This returns
Spiff is a 33 year old spaceman who fights Zorgs.
A value v with key k can be added to an existing
dictionary d with the syntax
d[k] = v.
For instance, (Filik et
al. 2019)
d = {} # Empty dictionary
d["irony"] = "The use of a word to mean its opposite."
d["sarcasm"] = "Irony intended to criticize."Dictionaries are mutable; therefore, we can change their contents, as in the following example:
d = {}
d["age"] = 33 # d is {"age": 33}
d["age"] = 31 # d is {"age": 31}Dictionaries have several handy methods; these are listed in tbl. 1.
| Methods | Descriptions |
|---|---|
d.clear() |
Clears all items from d |
d.copy() |
Returns a shallow copy of d |
dict.fromkeys(s[, v]) |
Returns a new dict with keys
from sequence s, each with optional
value v |
d.get(k) |
Returns the value for key k in d |
d.items() |
Returns a view object of key-value pairs in d |
d.keys() |
Returns a view object of keys in d |
d.pop(k) |
Removes and returns the value for key k in d |
d.popitem() |
Removes and returns the last-inserted key-value pair from d |
d.setdefault(k, v) |
Returns the value for the key k in
d; inserts v if absent |
d.update(d_) |
Updates d with key-value pairs from
another dictionary d_ |
d.values() |
Returns a view object of values in d |
Note that most of these methods apply to dictionary instance d, either mutating d or returning something from d. However, the fromkeys() method is called from the
class dict because it
has nothing to do with an instance. Such methods are called class methods; the other methods we’ve considered
thus far are instance methods.
Dictionary view objects—returned by
items(), keys(), and values()—are dynamically updating
objects that change with their dictionary. For instance,
d = {"a": 1, "b": 2}
d_keys = d.keys()
print(f"View object before: {d_keys}")
d["c"] = 3
print(f"View object after: {d_keys}")This returns
View object before: dict_keys(['a', 'b'])
View object after: dict_keys(['a', 'b', 'c'])
View objects can be converted to lists with the list()
function, as in list(d_keys).
Write a program that meets the following requirements:
- It defines a list of strings
names = ["Mo", "Jo", "Flo"] - It constructs a
dictinstancedatawith keys from the listnames - It creates and populates a sub-
dictwith the follow properties for each name:- Mo—year: sophomore, major: Mechanical Engineering, GPA: 3.44
- Jo—year: junior, major: Computer Science, GPA: 3.96
- Flo—year: sophomore, major: Philosophy, GPA: 3.12
- It prints each of the students’ name and year
- It replaces Jo’s GPA with 3.98 and prints this new value
- It removes the entry for Mo and prints a list of remaining keys in
data
The following program meets the given requirements:
names = ["Mo", "Jo", "Flo"]
data = dict.fromkeys(names) # => {"Mo": None, "Jo": None, "Flo": None}
#%% Populate Data
data["Mo"] = {}
data["Mo"]["year"] = "sophomore"
data["Mo"]["major"] = "Mechanical Engineering"
data["Mo"]["GPA"] = 3.44
data["Jo"] = {}
data["Jo"]["year"] = "junior"
data["Jo"]["major"] = "Computer Science"
data["Jo"]["GPA"] = 3.96
data["Flo"] = {}
data["Flo"]["year"] = "sophomore"
data["Flo"]["major"] = "Philosophy"
data["Flo"]["GPA"] = 3.12
#%% Data Operations and Printing
print(f"Mo is a {data['Mo']['year']}. "
f"Jo is a {data['Jo']['year']}. "
f"Flo is a {data['Flo']['year']}.")
data["Jo"]["GPA"] = 3.98
print(f"Jo's new GPA is {data['Jo']['GPA']}")
data.pop("Mo")
print(f"Names sans Mo: {list(data.keys())}")This prints the following in the console:
Mo is a sophomore. Jo is a junior. Flo is a sophomore.
Jo's new GPA is 3.98
Names sans Mo: ['Jo', 'Flo']
Online Resources for Section 1.8
No online resources.