CHAPTER 11
Working with Lists and Dictionaries
Python provides lists and dictionaries for storing data efficiently in variables. A list is a collection that can store multiple items of the same type or of different types and provides access to its items via an index. A dictionary is similar to a list but more powerful, allowing you to create collections of information that you access through named elements called keys.
Understanding Lists and Their Use
Locate Items and Access Data in a List
Understanding Dictionaries and Their Use
Create a Dictionary and Return Values
Meet Python’s Dictionary Methods
Create a Dictionary from an Existing Iterable
Add Key/Value Pairs to a Dictionary
Understanding Lists and Their Use
In Python, a list is an object that enables you to store multiple items within a single variable. The items can be of the same type or of different types. The list contains an index that enables you to set or retrieve the individual items. Technically, a list is a mutable sequence, so you can change the order of its items, add and remove items, sort the items, and so on.
A List Is Ordered and Indexed
In Python, a list is an ordered and indexed collection:
0
, the second item is item 1
, and so on. You use the index numbers to access the list items.List Items Are Mutable
The items in a list are mutable, so you can change a list after creating it. For example, you can add items to a list, remove items from it, or reverse its order.
Lists Can Contain Duplicate Values
A list can contain duplicate values, as there is no constraint requiring each value to be unique.
You can use the count()
method to count the number of items in a list that have a particular value.
Understanding How Lists Compare to Tuples and Sets
Table 11-1 summarizes the three key attributes of lists, tuples, and sets in Python.
Table 11-1: Attributes of Lists, Tuples, and Sets
Collection |
Mutable |
Ordered |
Duplicates Allowed |
---|---|---|---|
List |
Yes |
Yes |
Yes |
Set |
Yes |
No |
No |
Tuple |
No |
Yes |
Yes |
Understanding How Lists Compare to Sets
In Python, both a list and a set can contain various types of data, which gives you great flexibility at the risk of occasionally running into the wrong data type for your needs. Beyond that, however, lists differ significantly from sets.
First, a list is ordered, while a set is unordered. Second, a list can contain duplicates, whereas a set cannot contain duplicates. Third, and more technically, Python sets use hashing to store their values, which makes lookups in sets fast and efficient but means the order of a set’s items may vary.
Understanding How Lists Compare to Tuples
The key difference between a list and a tuple is that a list is mutable whereas a tuple is immutable. Both lists and tuples are ordered and can contain duplicate items. Both lists and tuples are sequential, which enables you to iterate through the items they contain.
Tuples’ immutability means that they are more memory efficient than lists and require less processing time. When your code contains data that will not need to be changed, you may be able to improve performance by using tuples rather than lists.
Understanding How Python Lists Compare to Arrays in Other Programming Languages
Python lists are similar to arrays in other programming languages, but lists offer greater flexibility. There are two main differences between lists and arrays.
First, when you create an array, you specify its data type, such as float; the array can contain only items that have that data type. By contrast, a list in Python can contain items of different data types, as needed.
Second, when you create an array, you specify the number of items it contains. Python allocates memory to store each potential item, but you do not need to populate each item immediately, or indeed ever. By contrast, a list’s size is dynamic, increasing as items are added, but each item must contain data, even if the data type is None.
Create a List
To create a list, you declare a variable; enter the assignment operator, =
; and then enter the list items, separated by commas, within square brackets. For example, the statement list1 = [1, 2, 3]
declares a variable named list1
and assigns to it three integers — 1
, 2
, and 3
.
In this section, you create three lists in a terminal window. The first list contains integers, the second list contains strings, and the third list contains four different data types.
Create a List
Open a terminal window and launch Python.
The Python prompt appears.
Type the following statement, which creates a variable named list1
and assigns five integers to it, and then press :
list1 = [1, 2, 3, 4, 5]
Type the following statement, which uses the print()
function to display the contents of list1
, and then press :
print(list1)
Python displays [1, 2, 3, 4, 5]
. The brackets indicate that the variable’s contents are a list.
Type the following statement, which creates a variable named list2
and assigns two strings to it, and then press :
list2 = ["Evie", "Frank"]
Type the following statement, which creates a variable named list3
and assigns several kinds of data to it. Press .
list3 = [11.5, "cats", True, 0]
Type the following statement to display the contents of list2
. Press .
print(list2)
Python displays ['Evie', 'Frank']
.
Type the following statement to display the contents of list3
. Press .
print(list3)
Python displays [11.5, 'cats', True, 0]
.
Meet Python’s List Methods
Python provides 11 methods for working with lists. Three of these methods — append()
, extend()
, and insert()
— enable you to add items to the list. Conversely, three other methods — clear()
, pop()
, and remove()
— enable you to remove one or all methods from the list. The other five methods enable you to sort the list, return an element by its position in the list, return the number of items that match specific criteria, and create a copy of the list.
Table 11-2 explains Python’s methods for working with lists.
Table 11-2: Methods for Working with Lists
Method |
Use This Method To |
---|---|
|
Add an element to the end of the list. |
|
Remove all the elements from the list. |
|
Create a copy of the list. |
|
Count the number of list elements that match the specified value. |
|
Extend the list by adding the elements from another list or other iterable. |
|
Return the index number of the first list element that matches the specified value. |
|
Insert an element in the list at the specified index position. |
|
Remove the list element at the specified index position. |
|
Remove the first list element that matches the specified value. |
|
Reverse the order of the whole list. |
|
Sort the list in ascending order, descending order, or ordered by the function specified. |
The following list provides examples of using these methods. You will use the methods more extensively during the first half of this chapter.
list4
and a list named list5
:
list4 = ["Brian", "Charlene", "Dan"]
list5 = ["Eva", "Finn"]
list4
:
list4.insert(0, "Abigail")
list4
by adding the elements from list5
:
list4.extend(list5)
Gloria
to the end of the list list4
:
list4.append("Gloria")
list4
alphabetically:
list4.sort()
list4
:
list4.pop(1)
list4
:
list4.clear()
Add Items to a List
Python’s lists are mutable, so you can change a list after creating it. Often, you will want to add items to the list, as explained here, or remove items from it, as explained in the following section, “Remove Items from a List.” You can use the append()
method to add a single element to the end of a list, use the insert()
method to insert an item at a specific index position in the list, or use the extend()
method to extend the list by adding items from another list or from another iterable element.
Add Items to a List
Open a terminal window and launch Python.
The Python prompt appears.
Type the following statement, which creates the variable n1
and assigns a list of two strings to it. Press .
n1 = ["Sam", "George"]
Type the following print()
statement, and then press , to display the contents of n1
:
print(n1)
Python displays ['Sam', 'George']
.
Type the following statement, which creates the variable n2
and assigns a list of two other strings to it. Press .
n2 = ["Antonia", "Brett"]
Type the following print()
statement, and then press , to display the contents of n2
:
print(n2)
Python displays ['Antonia', 'Brett']
.
Type the following statement, which uses the insert()
method to insert a string at position 1
— second — in n1.
Press .
n1.insert(1, "Helen")
Press four times, making Python enter the print(n1)
statement again, and then press .
print(n1)
Python displays ['Sam', 'Helen', 'George']
.
Type the following statement, which uses the extend()
method to add n2
to the end of n1
, and then press :
n1.extend(n2)
Press twice to enter the print(n1)
statement once more, and then press :
print(n1)
Python displays ['Sam', 'Helen', 'George', 'Antonia', 'Brett']
.
Type the following statement, which uses the append()
method to add a string to the end of n1
, and then press :
n1.append("Sia")
Press twice to enter the print(n1)
statement yet again, and then press .
print(n1)
Python displays ['Sam', 'Helen', 'George', 'Antonia', 'Brett', 'Sia']
.
Remove Items from a List
Python provides three methods for removing items from a list. When you need to remove a single item by specifying its index position, use the pop()
method. When you need to remove the first item that matches the value you specify, use the remove()
method; you may then need to check for other instances of the item in the list and remove them too if necessary. When you need to remove all the items from the list, use the clear()
method.
Remove Items from a List
In Visual Studio Code, create a new script, and then save it.
Type the following statement, which creates a variable named dx
and assigns to it a list of integers. Press .
dx = [1, 3, 4, 4, 4, 5, 7, 4, 8, 4, 11]
Type the following statement, which uses the print()
function to display a string giving the number of instances of 4
in the list. Press .
print("The list contains " + str(dx.count(4)) + " instances of 4.")
Type the following statement, which uses the index()
method to return the position of the first 4
in the dx
list and the print()
function to display a string announcing its removal. Press .
print("Removing the 4 at index position " + str(dx.index(4)) + ".")
Type the following statement, which uses the pop()
method of the dx
list to remove the first 4
by specifying its index position. Press .
dx.pop(dx.index(4))
Type the following statement, which starts a while
loop that runs while the count()
method returns more than one 4
in the dx
list. Press .
while dx.count(4) > 1:
Copy the step 4 statement and paste it onto the line after the while
line, accepting the indent that Visual Studio Code automatically applies.
print("The list contains " + str(dx.count(4)) + " instances of 4.")
Type the following statement, which creates a variable called msg
and assigns to it a string announcing the removal of the 4
at the index position it specifies. Press .
msg = "Removing the 4 at index position " + str(dx.index(4)) + "."
Type the following statement, which uses the remove()
method to remove the first instance of 4
from dx
. Press .
dx.remove(4)
Type the following statement, which uses the print()
function to display msg
. Press .
print(msg)
Press to remove the indent, ending the while
block, and then type the following statement to display the contents of dx
. Press .
print(dx)
Type the following statement, which uses the clear()
method to remove the contents of dx
. Press .
dx.clear()
Type the following statement to display the contents of dx
— nothing.
print(dx)
Click Run Python File in Terminal ().
The Terminal pane appears.
The print()
statements display the output as the while
loop whittles down the instances of 4
until only one remains.
Locate Items and Access Data in a List
Often, you will need to determine whether a list contains a particular item and, if it does, where that item is. Python provides the count()
method and the index()
method to take care of this need. You use the count()
method to return an integer value giving the number of elements in the list that match a specified value. If this number is greater than 0, you can use the index()
method to return the index number of the first item in the list that matches your specified value.
Locate Items and Access Data in a List
Open a terminal window and launch Python.
The Python prompt appears.
Type the following statement, which creates a variable named scores
and assigns to it a list containing several integers. Press .
scores = [20, 15, 40, 48, 15, 8]
Type the following statement, which uses the len()
function to return the number of items in the scores
list. Press .
print(len(scores))
Python displays 6
, the number of items.
Type the following statement, which uses the count()
method to determine the number of instances of 15
in scores
, and then press :
scores.count(15)
Python returns 2
, because the scores
list contains two instances of 15
.
Type the following statement, which uses the index()
method to return the index position of the first instance of 15
in the list. Press .
scores.index(15)
Python returns 1
, indicating that the first instance of 15
is at index position 1 in the list — in other words, it is the second item.
Type the following statement, which uses the count()
method to determine the number of instances of 36
in scores
, and then press :
scores.count(36)
Python displays 0
, because the scores
list contains no instances of 36
.
Type the following statement, which uses the index()
method to return the index position of the first instance of 36
in the list. Press .
scores.index(36)
Python returns an error: ValueError: 36 is not in list
.
Sort the Items in a List
Python provides two methods for sorting the items in a list. The reverse()
method simply reverses the current sort order of the list, so if you have a list named names1
that contains ["Alex", "Blake", "Cody")
, names1.reverse()
returns ["Cody", "Blake", "Alex"]
. The sort()
method is more widely useful, enabling you to sort a list in ascending order, in descending order, or in the order given by a function you specify.
Sort the Items in a List
Sort Using the sort()
Method and the reverse()
Method
Open a terminal window and launch Python.
The Python prompt appears.
Type the following statement, which creates a variable named k7
and assigns a list of three fruits to it. Press .
k7 = ["tomato", "avocado", "okra"]
Type the following statement, which sorts the k7
list into ascending order, and then press :
k7.sort()
Type the following statement, which displays the contents of k7
, and then press :
print(k7)
Python displays ['avocado', 'okra', 'tomato']
.
Type the following statement, which use the reverse
argument to sort the k7
list in descending order, and then press :
k7.sort(reverse = True)
Press twice to repeat the print(k7)
statement, and then press :
print(k7)
Python displays ['tomato', 'okra', 'avocado']
.
Type the following statement, which uses the reverse()
method to reverse the list’s order, and then press :
k7.reverse()
Press twice to repeat the print(k7)
statement again, and then press .
print(k7)
Python displays ['avocado', 'okra', 'tomato']
again.
Sort Using a Function That Provides Sort Criteria
Type the following function, which implements a crude sort by the last character of the input. Press at the end of each line, and then again to end the function and create a blank line.
def sort_by_last(n):
return n[-1]
Note: Indent the second line by four spaces.
Type the following statement, which creates a variable named animals
and assigns a list of three animals to it. Press .
animals = ["cat", "dog", "snake"]
Type the following statement, which uses the sort()
method to sort the animals
list by the sort_by_last
function. Press .
animals.sort(key=sort_by_last)
Type a print()
statement to display the contents of animals
, and then press :
print(animals)
Python displays ['snake', 'dog', 'cat']
, the terms sorted by their last letters.
Understanding Dictionaries and Their Use
In Python, a dictionary is an object that enables you to store collections of data. The items in the dictionary consist of key/value pairs, in which a key enables you to access the corresponding value — similar in concept to a conventional dictionary, in which you look up a term to find its meaning.
Technically, a dictionary is an ordered, mutable sequence, so you can add items, remove specific items, or simply delete the entire contents of the dictionary.
Understanding What Python Dictionaries Are
In Python, a dictionary is an ordered, mutable collection that cannot have duplicates:
Understanding the Layout of a Python Dictionary
To create a dictionary, you enter its key/value pairs within braces, {}
. Usually, you assign the entire dictionary to a variable so that you can refer to it easily. For example, the following statement creates a variable named dog0
and assigns to it a dictionary consisting of a single key/value pair, the key being name
and the value being Spot
:
dog0 = {"name": "Spot"}
You can create a dictionary on a single line of code, as in the following example, which shows a single logical line wrapped to multiple physical lines by the constraints of the book.
dog1 = {"name": "Minnie", "breed": "Chihuahua", "weight": 5, "height": 6, "age": 6}
Normally, however, it is more convenient to break the dictionary over multiple lines of code, using the kind of layout shown in the following example:
dog2 = {
"name": "Max",
"breed": "Newfoundland",
"weight": 130,
"height": 30,
"age": 4
}
Here, each key — name
, breed
, and so on — appears on a separate line followed by a colon and its value, making the code easier to read quickly.
You Access Dictionary Items by Key
To access an item in a dictionary, you specify the item’s key. For example, to access the value for the breed
key in the dog2
dictionary, you specify dog2["breed"]
.
Dictionaries Are Ordered in Python 3.7 Onward
Python 3.7 changed dictionaries from unordered collections to ordered collections. If you are using Python 3.6 or an earlier version, your code’s dictionaries will be unordered — that is, the items in a dictionary will be in an order, but that order will not be fixed.
As long as you access your dictionary items by key, it makes little difference whether the dictionary items are ordered or unordered. But if you access your dictionary items by index position — for example, by creating a list of the dictionary’s keys and using that to determine a key’s position — you should be aware of the difference, because in Python 3.6 or earlier the items’ index positions are likely to change.
Create a Dictionary and Return Values
When you need to store data in a container that enables you to look up elements of the data quickly and easily, create a dictionary and assign it to a variable. You enter the entire dictionary within braces, {}
, using a colon to connect each key to its value and a comma to separate each key/value pair from the next pair.
You can then either display the entire dictionary — for example, to verify its contents and completeness — or return individual values by specifying their keys.
Create a Dictionary and Return Values
Open a terminal window and launch Python.
The Python prompt appears.
Type the following statement, which creates a variable named dog3
and assigns to it a dictionary containing several canine attributes. Press at the end of each line.
dog3 = {
"name": "Belle",
"breed": "Rottweiler",
"weight": 125,
"height": 26,
"age": 8
}
Type the following statement, which uses the print()
function to display the entire dog3
dictionary. Press .
print(dog3)
Python displays the dictionary’s keys and values on a single logical line, wrapped here:
{'name': 'Belle', 'breed': 'Rottweiler', 'weight': 125, 'height': 26, 'age': 8}
Type the following statement, which uses the print()
function to display the breed
key from the dog3
dictionary. Press .
print(dog3["breed"])
Python displays Rottweiler
.
Meet Python’s Dictionary Methods
Python provides 11 methods for working with dictionaries. Five of these methods — fromkeys()
, get()
, items()
, keys()
, and values()
— enable you to retrieve information from a dictionary. On the other side of the coin, three methods — pop()
, popitem()
, and clear()
— enable you to remove one or more entries from the dictionary. One method, update()
, lets you insert key/value pairs. One method, setdefault()
, does double duty, returning information if it is there and adding it if it is not. Finally, the copy()
method enables you to copy an entire dictionary.
Table 11-3 explains Python’s methods for working with dictionaries.
Table 11-3: Methods for Working with Dictionaries
Method |
Use This Method To |
---|---|
|
Remove all the key/value pairs from the dictionary. |
|
Create a copy of the entire dictionary. |
|
Return a dictionary containing the specified keys and their values from this dictionary. |
|
Return the value of the specified key. |
|
Return a list containing a tuple for each key/value pair in the dictionary. |
|
Return a list of the dictionary’s keys, without their values. |
|
Remove the items whose key you have specified. |
|
Remove the last key/value pair inserted in the dictionary. |
|
Return the value of the specified key, if it exists; if it does not exist, insert the key and assign it the specified value. |
|
Insert the specified key/value pairs in the dictionary. |
|
Return a list of all the dictionary’s values. |
The following list provides quick examples of using these methods. You will use the methods more extensively during the remainder of this chapter:
dog3
dictionary:
>>> dog3.keys
dict_keys(['name', 'breed', 'weight', 'height', 'age'])
id_chip
, in the dog3
dictionary:
>>> dog3.update({"id_chip": "yes"})
coat
, if it exists, and assign the given value if the key does not exist. In the first instance, the key does not exist, so Python creates it and assigns the value provided. In the second instance, the key exists, so Python returns the current value.
>>> dog3.setdefault("coat", "short")
'short'
>>> dog3.setdefault("coat", "long")
'short'
Create a Dictionary from an Existing Iterable
Python’s fromkeys()
method enables you to create a dictionary whose keys come from an existing iterable, such as a list, a set, or another dictionary. This way of creating a dictionary is convenient when you have an iterable that contains the data required for the keys in a new dictionary you want to create. The fromkeys()
method lets you either assign the same value to each of the key/value pairs or not assign a value, leaving the values blank until you populate them otherwise.
Create a Dictionary from an Existing Iterable
Open a terminal window and launch Python.
The Python prompt appears.
Type the following statement, which creates a variable named pet_factor
and assigns to it a list of factors to consider when choosing a pet. Press .
pet_factor = ["space", "character", "cost", "interactivity"]
Type the following statement, which creates a variable named considerations
and assigns to it a dictionary whose keys are derived by using the fromkeys()
method on the pet_factor
list. Press .
considerations = dict.fromkeys(pet_factor)
Type the following statement, which uses the print()
function to display the contents of considerations
. Press .
print(considerations)
Python displays {'space': None, 'character': None, 'cost': None, 'interactivity': None}
.
Note: Each key contains the value None
because the fromkeys()
method in step 3 did not assign a value to the keys.
Type the following statement, which creates a variable named pet_pros
and assigns to it a list of benefits of having a pet. Press .
pet_pros = ["companionship", "affection", "exercise", "memory", "schedule"]
Type the following statement, which creates a variable called cat
and assigns to it a dictionary whose keys are derived by using the fromkeys()
method on the pet_pros
list. The statement assigns a default value of True
to each key. Press .
cat = dict.fromkeys(pet_pros, True)
Type the following print()
statement to display the contents of cat
, and then press :
print(cat)
Python displays {'companionship': True, 'affection': True, 'exercise': True, 'memory': True, 'schedule': True}
.
You can now change the values of the keys, as needed.
Add Key/Value Pairs to a Dictionary
When you need to add one or more key/value pairs to a dictionary, use the update()
method. You can either add the key/value pairs by providing their information directly or add them from an iterable object — for example, from another dictionary. The update()
method places the new key/value pairs at the end of the dictionary.
You can also add a key/value pair to a dictionary by using the setdefault()
method. If the key/value pair already exists, this method returns the current value. If the key/value pair does not exist, this method creates the pair and assigns the value you provide.
Add a Key/Value Pair to a Dictionary
Open a terminal window and launch Python.
The Python prompt appears.
Type the following statement, which creates a variable named dog4
and assigns to it a dictionary containing a single key/value pair. Press .
dog4 = {"name": "Rex"}
Type the following statement, which uses the update()
method to add one key/value pair to dog4
, and then press :
dog4.update({"breed": "Newfoundland"})
Type the following print()
statement, and then press :
print(dog4)
Python displays {'name': 'Rex', 'breed': 'Newfoundland'}
.
Type the following update()
statement, which adds two more key/value pairs, and then press :
dog4.update({"age": 5, "color": "black"})
Press twice to enter the print()
statement again, and then press :
print(dog4)
Python displays {'name': 'Rex', 'breed': 'Newfoundland'
, 'age': 5, 'color': 'black'}}
.
Type the following statement, which creates a variable named stats
and assigns it a dictionary containing two key/value pairs. Press .
stats = {"height": 28, "weight": 146}
Type the following statement, which uses the update()
method to insert the key/value pairs from stats
into dog4
. Press .
dog4.update(stats)
Press thrice to enter the print()
statement again, and then press :
print(dog4)
Python displays {'name': 'Rex', 'breed': 'Newfoundland', 'age': 5, 'color': 'black', 'height': 28, 'weight': 146}
.
Type the following statement, which uses the setdefault()
method to return the value of the breed
key, if it exists, and to create the key/value pair if it does not. Press .
dog4.setdefault("breed")
Python returns 'Newfoundland'
, because the breed
key does exist.
Type the following statement, which uses the setdefault()
method to return the value of the temperament
key, if it exists, and to create the key/value pair if it does not. Press .
dog4.setdefault("temperament", "amiable")
Python returns 'amiable'
, which tells you that the temperament
key’s value is amiable
.
Type the following print()
statement, which displays the temperament
key’s value, and then press :
print(dog4["temperament"])
Python displays amiable
.
Remove Key/Value Pairs from a Dictionary
Python provides three methods that enable you to remove key/value pairs from a dictionary. First, you can use the pop()
method to remove an item by specifying its key. Second, you can use the popitem()
method to remove the last key/value pair that was added to the dictionary; because Python places the newest key at the end of the dictionary, this method removes the last key and its value. Finally, you can use the clear()
method to remove all keys and their values from the dictionary, leaving the dictionary empty.
Remove Key/Value Pairs from a Dictionary
Open a terminal window and launch Python.
The Python prompt appears.
Type the following statement, which creates a variable named ocelot
and assigns to it a dictionary containing eight key/value pairs. Press .
ocelot = {
… "Kingdom": "Animalia",
… "Phylum": "Chordata",
… "Class": "Mammalia",
… "Order": "Carnivora",
… "Suborder": "Feliformia",
… "Family": "Felidae",
… "Subfamily": "Felinae",
… "Genus": "Leopardus"
… }
Type the following statement, which uses the popitem()
method to remove the last key/value pair. Press .
ocelot.popitem()
Python displays ('Genus', 'Leopardus')
to indicate that it has removed the Genus
key, whose value was Leopardus
.
Note: In Python versions 3.6 and earlier, the popitem()
method removes a random key/value pair from the dictionary rather than the last pair.
Type the following statement, which uses the popitem()
method again but this time assigns the resulting tuple to a variable named y
. Press .
y = ocelot.popitem()
Type the following print()
statement to display the contents of y
. Press .
print(y)
Python displays ('Subfamily', 'Felinae')
.
Type the following statement, which uses the pop()
method to remove the Class
key, and then press :
ocelot.pop("Class")
Python displays 'Mammalia'
to indicate the value that was assigned to the key it has removed.
Type the following print()
statement to display the contents of the ocelot
dictionary as they now stand. Press .
print(ocelot)
Python displays {'Kingdom': 'Animalia', 'Phylum': 'Chordata', 'Order': 'Carnivora', 'Suborder': 'Feliformia', 'Family': 'Felidae'}
.
Type the following statement, which uses the clear()
method to remove the dictionary’s contents, and then press .
ocelot.clear()
Press twice to enter the print()
statement again, and then press :
print(ocelot)
Python displays {}
, indicating that the dictionary is empty.
Return Keys and Values from a Dictionary
You can return a value from a dictionary by entering the corresponding key’s name in brackets after the dictionary’s name — for example, dog1["breed"]
returns the value of the breed
key in the dictionary called dog1
. Alternatively, you can use the get()
method to return the value for a specific key.
You can use the keys()
method to return all of a dictionary’s keys, use the values()
method to return all its values, or use the items()
method to return both the keys and the values. These three methods return views that update automatically when the dictionary’s contents change.
Return Keys and Values from a Dictionary
Open a terminal window and launch Python.
The Python prompt appears.
Type the following statement to create a variable called dog5
and assign to it a dictionary containing a canine’s key attributes. Press .
dog5 = {
… "name": "Hondje",
… "breed": "Boerboel",
… "height": 24,
… "weight": 70
… }
Type the following statement, which uses the get()
method to return the value of the breed
key. Press .
dog5.get("breed")
Python returns 'Boerboel'
.
Type the following statement, which uses the keys()
method and displays all the keys in the dog5
dictionary, and then press :
print(dog5.keys())
Python displays dict_keys(['name', 'breed', 'height', 'weight'])
.
Note: The keys()
method returns a list containing the keys. Similarly, the values()
method returns a list containing the values.
Type the following statement, which uses the values()
method and displays all the values in the dog5
dictionary, and then press :
print(dog5.values())
Python displays dict_values(['Hondje', 'Boerboel', 24, 70])
.
Type the following statement, which creates a variable named q
and assigns to it the result of using the items()
method on the dog5
dictionary. Press .
q = dog5.items()
Note: The items()
method returns a list of tuples, each containing a key/value pair.
Type the following statement, which uses the print()
function to display the contents of q
. Press .
print(q)
Python displays dict_items([('name', 'Hondje'), ('breed', 'Boerboel'), ('height', 24), ('weight', 70)])
.
3.136.18.61