Python 简明教程
Python - Access Dictionary Items
Access Dictionary Items
在 Python 中访问 dictionary 涉及检索与字典数据结构中的特定键关联的值。字典由键值对组成,每个键都是唯一的,并映射到相应的值。访问字典项允许您通过提供相应的键来检索这些值。
Accessing dictionary items in Python involves retrieving the values associated with specific keys within a dictionary data structure. Dictionaries are composed of key-value pairs, where each key is unique and maps to a corresponding value. Accessing dictionary items allows you to retrieve these values by providing the respective keys.
在 Python 中访问字典项有各种方法。它们包括:
There are various ways to access dictionary items in Python. They include −
-
Using square brackets []
-
The get() method
-
Iterating through the dictionary using loops
-
Or specific methods like keys(), values(), and items()
我们将详细讨论每种方法,以了解如何访问和检索字典中的数据。
We will discuss each method in detail to understand how to access and retrieve data from dictionaries.
Access Dictionary Items Using Square Brackets []
在 Python 中,方括号 [] 用于创建列表、从列表或其他可迭代对象(如字符串、元组或字典)访问元素,以及用于列表解析。
In Python, the square brackets [] are used for creating lists, accessing elements from a list or other iterable objects (like strings, tuples, or dictionaries), and for list comprehension.
我们可以通过在括号中提供键来使用方括号访问字典项。这检索与指定键关联的值。
We can access dictionary items using square brackets by providing the key inside the brackets. This retrieves the value associated with the specified key.
Example 1
在以下示例中,我们定义了一个名为“capitals”的字典,其中每个键代表一个州,其对应的值代表首府。
In the following example, we are defining a dictionary named "capitals" where each key represents a state and its corresponding value represents the capital city.
然后,我们使用字典中的相应键‘Gujarat’和‘Karnataka’访问和检索 Gujarat 和 Karnataka 的首府−
Then, we access and retrieve the capital cities of Gujarat and Karnataka using their respective keys 'Gujarat' and 'Karnataka' from the dictionary −
capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
print ("Capital of Gujarat is : ", capitals['Gujarat'])
print ("Capital of Karnataka is : ", capitals['Karnataka'])
它将生成如下输出:
It will produce the following output −
Capital of Gujarat is: Gandhinagar
Capital of Karnataka is: Bengaluru
Example 2
如果方括号中给出的键不在字典对象中,Python 会引发 KeyError −
Python raises a KeyError if the key given inside the square brackets is not present in the dictionary object −
capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
print ("Captial of Haryana is : ", capitals['Haryana'])
以下是获得的错误 −
Following is the error obtained −
print ("Captial of Haryana is : ", capitals['Haryana'])
~~~~~~~~^^^^^^^^^^^
KeyError: 'Haryana'
Access Dictionary Items Using get() Method
Python 的 dict 类的 get() method 用于检索与指定键关联的值。如果键在字典中找不到,它将返回一个默认值(通常为 None),而不是引发 KeyError。
The get() method in Python’s dict class is used to retrieve the value associated with a specified key. If the key is not found in the dictionary, it returns a default value (usually None) instead of raising a KeyError.
我们可以通过指定键作为参数来使用 get() 方法访问字典项。如果键存在于字典中,该方法将返回关联的值;否则,将返回一个默认值,除非另有规定,否则通常为 None。
We can access dictionary items using the get() method by specifying the key as an argument. If the key exists in the dictionary, the method returns the associated value; otherwise, it returns a default value, which is often None unless specified otherwise.
Syntax
以下是 Python 中 get() 方法的语法 −
Following is the syntax of the get() method in Python −
Val = dict.get("key")
其中 key 是不可变对象,用作字典对象中的键。
where, key is an immutable object used as key in the dictionary object.
Example 1
在以下示例中,我们定义了一个名为“capitals”的字典,其中每个键值对将一个州映射到其首府。然后,我们使用 get() 方法检索“Gujarat”和“Karnataka”的首府−
In the example below, we are defining a dictionary named "capitals" where each key-value pair maps a state to its capital city. Then, we use the get() method to retrieve the capital cities of "Gujarat" and "Karnataka" −
capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
print ("Capital of Gujarat is: ", capitals.get('Gujarat'))
print ("Capital of Karnataka is: ", capitals.get('Karnataka'))
我们得到了如下输出 −
We get the output as shown below −
Capital of Gujarat is: Gandhinagar
Capital of Karnataka is: Bengaluru
Example 2
与 “[]” 运算符不同,如果找不到键,get() 方法不会引发错误;它返回 None −
Unlike the "[]" operator, the get() method doesn’t raise error if the key is not found; it return None −
capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
print ("Capital of Haryana is : ", capitals.get('Haryana'))
它将生成如下输出:
It will produce the following output −
Capital of Haryana is : None
Example 3
get() 方法接受一个可选的 string 参数。如果参数已给,且未找到键,则此字符串变为返回值 −
The get() method accepts an optional string argument. If it is given, and if the key is not found, this string becomes the return value −
capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
print ("Capital of Haryana is : ", capitals.get('Haryana', 'Not found'))
执行上面的代码后,我们得到以下输出: -
After executing the above code, we get the following output −
Capital of Haryana is: Not found
Access Dictionary Keys
在一个字典中,键与每个值关联的唯一标识符。它们充当标签或索引,允许访问并检索相应的价值。键是不可变的,这意味着一旦分配键,它们就不能被更改。它们必须为不可变数据类型,例如字符串、数字或元组。
In a dictionary, keys are the unique identifiers associated with each value. They act as labels or indices that allow you to access and retrieve the corresponding value. Keys are immutable, meaning they cannot be changed once they are assigned. They must be of an immutable data type, such as strings, numbers, or tuples.
我们可使用返回包含字典中所有键的视图对象的 keys() 方法来访问 Python 中的字典键。
We can access dictionary keys in Python using the keys() method, which returns a view object containing all the keys in the dictionary.
Example
在此示例中,我们通过 keys() 方法从字典 "student_info" 检索所有键 −
In this example, we are retrieving all the keys from the dictionary "student_info" using the keys() method −
# Creating a dictionary with keys and values
student_info = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}
# Accessing all keys using the keys() method
all_keys = student_info.keys()
print("Keys:", all_keys)
以下是上面代码的输出: -
Following is the output of the above code −
Keys: dict_keys(['name', 'age', 'major'])
Access Dictionary Values
在一个字典中,值与每个唯一键关联的数据。它们表示存储在字典中的实际信息,并且可以为任何数据类型,例如字符串、整数、列表、其他字典等等。字典中的每个键都映射到特定值,形成为键值对。
In a dictionary, values are the data associated with each unique key. They represent the actual information stored in the dictionary and can be of any data type, such as strings, integers, lists, other dictionaries, and more. Each key in a dictionary maps to a specific value, forming a key-value pair.
我们可使用以下方式访问 Python 中的字典值 −
We can access dictionary values in Python using −
-
Square Brackets ([]) − By providing the key inside the brackets.
-
The get() Method − By calling the method with the key as an argument, optionally providing a default value.
-
The values() Method − which returns a view object containing all the values in the dictionary
Example 1
在此示例中,我们直接使用方括号访问与键 "name" 和 "age" 关联的值 −
In this example, we are directly accessing associated with the key "name" and "age" using the sqaure brackets −
# Creating a dictionary with student information
student_info = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}
# Accessing dictionary values using square brackets
name = student_info["name"]
age = student_info["age"]
print("Name:", name)
print("Age:", age)
上述代码的输出如下:
Output of the above code is as follows −
Name: Alice
Age: 21
Example 2
在此,我们使用 get() 方法检索与键 "major" 关联的值,并为键 "graduation_year" 提供默认值 "2023" −
In here, we use the get() method to retrieve the value associated with the key "major" and provide a default value of "2023" for the key "graduation_year" −
# Creating a dictionary with student information
student_info = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}
# Accessing dictionary values using the get() method
major = student_info.get("major")
# Default value provided if key is not found
grad_year = student_info.get("graduation_year", "2023")
print("Major:", major)
print("Graduation Year:", grad_year)
我们按如下方式获得结果 −
We get the result as follows −
Major: Computer Science
Graduation Year: 2023
Example 3
现在,我们使用 values() 方法从字典 "student_info" 检索所有值 −
Now, we are retrieving all the values from the dictionary "student_info" using the values() method −
# Creating a dictionary with keys and values
student_info = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}
# Accessing all values using the values() method
all_values = student_info.values()
print("Values:", all_values)
获得的结果如下所示 −
The result obtained is as shown below −
Values: dict_values(['Alice', 21, 'Computer Science'])
Access Dictionary Items Using the items() Function
items() 函数在 Python 中用于返回视图对象,该对象显示字典的键值元组对的列表。
The items() function in Python is used to return a view object that displays a list of a dictionary’s key-value tuple pairs.
此视图对象可用于同时迭代字典的键和值,从而很容易在单个循环中访问键和值。
This view object can be used to iterate over the dictionary’s keys and values simultaneously, making it easy to access both the keys and the values in a single loop.
Example
在以下示例中,我们正在使用 items() 函数从字典 "student_info" 检索所有键值对 −
In the following example, we are using the items() function to retrieve all the key-value pairs from the dictionary "student_info" −
# Creating a dictionary with student information
student_info = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}
# Using the items() method to get key-value pairs
all_items = student_info.items()
print("Items:", all_items)
# Iterating through the key-value pairs
print("Iterating through key-value pairs:")
for key, value in all_items:
print(f"{key}: {value}")
以下是上面代码的输出: -
Following is the output of the above code −
Items: dict_items([('name', 'Alice'), ('age', 21), ('major', 'Computer Science')])
Iterating through key-value pairs:
name: Alice
age: 21
major: Computer Science