Python dictionary: how to get the value corresponding to the key

Table of contents

What is a dictionary in python

How to judge whether the key is in the dictionary

How to get the value corresponding to the key

Summarize


What is a dictionary in python

In Python, a dictionary (Dictionary) is an unordered and mutable data type used to store key-value (Key-Value) pairs. Dictionaries use keys to access and manipulate their corresponding values, rather than using indexes.

 

The characteristics of the dictionary are as follows:

1. Key uniqueness: The key in the dictionary must be unique, and a key can only correspond to one value. If you add the same key repeatedly, later values ​​will overwrite earlier ones.

2. Unordered: The key-value pairs in the dictionary have no fixed order. Even if the order of adding is different, the traversal order of the dictionary may be different.

3. Mutability: The key-value pairs in the dictionary can be added, deleted and modified.

A dictionary is defined with curly braces `{}`, each key-value pair in it is separated by a colon `:`, and the key and value are separated by a comma `,`. Example:

# 创建一个字典
person = {"name": "Alice", "age": 25, "city": "New York"}

# 访问字典中的值
print(person["name"])  # 输出: Alice
print(person["age"])   # 输出: 25

# 修改字典中的值
person["age"] = 26
print(person["age"])   # 输出: 26

# 添加新的键值对
person["gender"] = "Female"
print(person)          # 输出: {'name': 'Alice', 'age': 26, 'city': 'New York', 'gender': 'Female'}

# 删除键值对
del person["city"]
print(person)          # 输出: {'name': 'Alice', 'age': 26, 'gender': 'Female'}

In addition to the above operations, the dictionary also provides many methods and functions to perform operations such as traversal, search, sorting, and conversion according to requirements to meet different programming needs.

How to judge whether the key is in the dictionary

In Python, you can use the following methods to determine whether a key exists in a dictionary:

 

1. Use the `in` keyword: You can use the `in` keyword to check whether a key exists in the dictionary. The expression returns `True` if the key exists in the dictionary, otherwise returns `False`.
      

  my_dict = {"name": "Alice", "age": 25}
   
   if "name" in my_dict:
       print("键 'name' 存在于字典中")
   else:
       print("键 'name' 不存在于字典中")

2. Use the `dict.get(key)` method: `get()` method can be used to get the value of the specified key, if the key does not exist in the dictionary, return the default value (the default is `None`). This feature can be used to determine whether a key exists.

 

   my_dict = {"name": "Alice", "age": 25}
   
   if my_dict.get("name") is not None:
       print("键 'name' 存在于字典中")
   else:
       print("键 'name' 不存在于字典中")

Note: When using the `in` keyword, the dictionary will be searched in all keys, this search is very efficient, and its time complexity is O(1). The time complexity of using the `dict.get(key)` method is O(1) when the key exists, but when the key does not exist, the time complexity is O(1)~O(n), where n is The number of key-value pairs in the dictionary.

According to specific needs, you can choose a suitable method to determine whether a key exists in the dictionary.

How to get the value corresponding to the key

To get the value corresponding to a particular key from a dictionary, you can use the following methods:

 

1. Use the indexing operator `[]`: access the values ​​in the dictionary directly by enclosing the keys in square brackets.

 

my_dict = {"name": "Alice", "age": 25}
   
   name = my_dict["name"]
   print(name)  # 输出: Alice


   
   Using the index operator will raise a `KeyError` exception if the key does not exist in the dictionary. The `dict.get(key)` method can be used to avoid this exception and return the default value.

2. Use the `dict.get(key)` method: `get()` method can be used to get the value of the specified key, if the key does not exist in the dictionary, return the default value (the default is `None`).

 

my_dict = {"name": "Alice", "age": 25}
   
   name = my_dict.get("name")
   print(name)  # 输出: Alice
   
   address = my_dict.get("address", "N/A")
   print(address)  # 输出: N/A


   A default value can be set by passing a second parameter in the `get()` method, which is returned if the key does not exist.

3. Use the `dict.setdefault(key, default)` method: The `setdefault()` method is similar to the `get()` method, used to get the value of the specified key, and insert the key if it does not exist in the dictionary - default value pair, and returns the default value.

   

my_dict = {"name": "Alice", "age": 25}
   
   name = my_dict.setdefault("name", "Unknown")
   print(name)  # 输出: Alice
   
   address = my_dict.setdefault("address", "N/A")
   print(address)  # 输出: N/A
   
   print(my_dict)  # 输出: {'name': 'Alice', 'age': 25, 'address': 'N/A'}

These methods have different characteristics in obtaining the value corresponding to the key. Depending on your specific needs, you can choose an appropriate method to extract the value of a specific key in the dictionary.

Summarize

To sum up, there are several ways to get the value corresponding to the key in the dictionary:

1. Use the indexing operator `[]`: access the value in the dictionary directly by placing the key in square brackets. If the key does not exist, a `KeyError` exception is raised.

2. Use `dict.get(key)` method: `get()` method can get the value of the specified key, if the key does not exist, return the default value (the default is `None`).

3. Use `dict.setdefault(key, default)` method: `setdefault()` method is used to get the value of the specified key, if the key does not exist, insert the key-default value pair and return the default value.

These methods provide flexible ways to obtain the value corresponding to the key in the dictionary according to different scenarios and requirements. When in use, you can choose a suitable method according to your needs, and handle the situation that the key does not exist, so as to ensure the correctness and stability of the program.

Guess you like

Origin blog.csdn.net/weixin_43856625/article/details/132015579