How to access the key-value pairs in a dictionary using Python?
In Python, there are several methods that can be used to retrieve a dictionary’s key-value pairs.
- list of keys
my_dict = {"a": 1, "b": 2, "c": 3}
keys = my_dict.keys()
print(keys) # 输出:dict_keys(['a', 'b', 'c'])
Note: the keys() method returns an iterable object, which needs to be converted into a list using the list() function.
- retrieve all the values from a collection
my_dict = {"a": 1, "b": 2, "c": 3}
values = my_dict.values()
print(values) # 输出:dict_values([1, 2, 3])
Note: the values() method also returns an iterable object.
- List of objects
my_dict = {"a": 1, "b": 2, "c": 3}
items = my_dict.items()
print(items) # 输出:dict_items([('a', 1), ('b', 2), ('c', 3)])
Note: the items() method returns an iterable object containing key-value pairs, where each pair is represented as a tuple.
- Iterate through key-value pairs in a dictionary using a loop.
my_dict = {"a": 1, "b": 2, "c": 3}
for key, value in my_dict.items():
print(key, value)
Output:
a 1
b 2
c 3
In a loop, you can assign keys and values to variables using destructuring assignment.
In summary, there are several ways to access the key-value pairs of a dictionary: use the keys() method to get keys, use the values() method to get values, use the items() method to get key-value pairs, or iterate through the dictionary’s key-value pairs.