Python language basics 55: items and values in a dictionary
October 11, 2015 Leave a comment
Introduction
In the previous post we saw how to copy a set. Both the copy function and the set constructor create shallow copies with all its consequences.
In this post we’ll discuss how to retrieve and iterate over the keys and values of a dictionary.
Looping through a dictionary
We’ve already seen how to loop through a dictionary with a for-each loop in this post. Here’s a reminder:
sizes = {"S": "Small", "M": "Medium", "L": "Large", "XL": "X-Large"}
Here’s how we can print the key and value of each element in a for-loop:
for size in sizes: print("Key ", size, ", value: ", sizes[size])
…which prints the following:
Key L , value: Large
Key S , value: Small
Key M , value: Medium
Key XL , value: X-Large
However, there are other key and value related functions available for a dictionary.
Keys only
You can get hold of the keys only using the keys function:
for key in sizes.keys(): print(key)
XL
M
L
S
Note that there’s no predefined sort order for the items in the dictionary. If you test the above code you may very well see a different key order.
Values only
There’s an equivalent function to retrieve the values in the dictionary:
for val in sizes.values(): print(val)
Medium
Small
Large
X-Large
Values and items
Finally there’s the items function which returns the key-value pairs in a tuple:
for item in sizes.items(): print(item)
(‘M’, ‘Medium’)
(‘L’, ‘Large’)
(‘S’, ‘Small’)
(‘XL’, ‘X-Large’)
The elements in the tuple can be assigned to comma-delimited variables for convenient access:
for key, value in sizes.items(): print("Key: {0}, value: {1}".format(key, value))
Key: L, value: Large
Key: S, value: Small
Key: M, value: Medium
Key: XL, value: X-Large
In the next post we’ll see how to update a dictionary.
Read all Python-related posts on this blog here.