Master all the usage of python array dictionary dict() in one article (zero-based learning python (3))

When we need to store and access key-value pair data in Python, it is better to use dictionaries. In the code samples below, I'll walk through various uses and instances of Python dictionaries.

create dictionary

An empty dictionary can be created using curly braces {} or the dict() function. The following code example demonstrates how to create a dictionary:

# 创建空字典
empty_dict = {
    
    }
print(empty_dict)

# 使用字面量创建字典
person_dict = {
    
    "name": "Alice", "age": 25, "city": "New York"}
print(person_dict)

# 使用 dict() 函数创建字典
fruit_dict = dict(apple=3, banana=2, cherry=5)
print(fruit_dict)

Access dictionary elements

Elements in the dictionary can be accessed by key. If the key does not exist, Python will raise a KeyError exception. The following code example demonstrates how to access dictionary elements:

person_dict = {
    
    "name": "Alice", "age": 25, "city": "New York"}

# 通过键访问字典元素
print(person_dict["name"])
print(person_dict["age"])
print(person_dict["city"])

# 尝试访问不存在的键会引发 KeyError 异常
# print(person_dict["gender"])

Add and update dictionary elements

Elements can be added or updated to the dictionary using the assignment operator or the update() method. If the key does not exist, the new element will be added; if the key already exists, the existing value will be updated. The following code example demonstrates how to add and update dictionary elements:

fruit_dict = {
    
    "apple": 3, "banana": 2, "cherry": 5}

# 添加新元素
fruit_dict["orange"] = 4
print(fruit_dict)

# 更新现有值
fruit_dict["banana"] = 7
print(fruit_dict)

# 使用 update() 方法添加多个元素
fruit_dict.update({
    
    "pear": 6, "kiwi": 8})
print(fruit_dict)

delete dictionary element

Elements can be removed from the dictionary using the del keyword or the pop() method. If the key does not exist, a KeyError exception will be raised. The following code example demonstrates how to delete dictionary elements:

fruit_dict = {
    
    "apple": 3, "banana": 2, "cherry": 5}

# 删除指定键的元素
del fruit_dict["banana"]
print(fruit_dict)

# 使用 pop() 方法删除指定键的元素
fruit_dict.pop("cherry")
print(fruit_dict)

# 尝试删除不存在的键会引发 KeyError 异常
# del fruit_dict["orange"]
# fruit_dict.pop("orange")

dictionary traversal

A for loop can be used to iterate over the keys, values, or key-value pairs in a dictionary. The following code example demonstrates how to iterate over a dictionary:

fruit_dict = {
    
    "apple": 3, "banana": 2, "cherry": 5}

# 遍历键
for key in fruit_dict:
    print(key)

# 遍历值
for value in fruit_dict.values():
    print(value)

# 遍历键值对
for key, value in fruit_dict.items():
    print(key, value)

dictionary comprehension

Dictionary comprehensions can be used to create new dictionaries based on filters or transformations of existing dictionaries. The following code example demonstrates how to use dictionary comprehensions:

fruit_dict = {
    
    "apple": 3, "banana": 2, "cherry": 5}

# 筛选出数量大于 3 的水果
filtered_dict = {
    
    "apple": 3, 
                 key: value for key, value in fruit_dict.items() if value > 3}
print(filtered_dict)

# 将所有水果数量乘以 2
multiplied_dict = {
    
    key: value * 2 for key, value in fruit_dict.items()}
print(multiplied_dict)

A dictionary in Python is a very commonly used data structure that can store a series of key-value pairs, where each key is unique. A dictionary is a mutable data type that can dynamically add, remove, and modify key-value pairs. Here are some advanced uses of Python dictionaries:

Dictionary key-value pair exchange

The keys and values ​​of a dictionary can be swapped using:

my_dict = {
    
    'apple': 1, 'banana': 2, 'orange': 3}
new_dict ={
    
    value: key for key, value in my_dict.items()}
print(new_dict)
# 输出:{1: 'apple', 2: 'banana', 3: 'orange'}

Dictionary sorting

The dictionary itself is not ordered, but the keys or values ​​of the dictionary can be sorted by the following methods:

# 按照键排序
my_dict = {
    
    'apple': 1, 'banana': 2, 'orange': 3}
sorted_dict = {
    
    key: my_dict[key] for key in sorted(my_dict)}
print(sorted_dict)
# 输出:{'apple': 1, 'banana': 2, 'orange': 3}

# 按照值排序
my_dict = {
    
    'apple': 1, 'banana': 2, 'orange': 3}
sorted_dict = {
    
    key: value for key, value in sorted(my_dict.items(), key=lambda item: item[1])}
print(sorted_dict)
# 输出:{'apple': 1, 'banana': 2, 'orange': 3}

Merge of dictionaries

One dictionary can be merged into another using the update() method:

dict1 = {
    
    'apple': 1, 'banana': 2}
dict2 = {
    
    'orange': 3, 'pear': 4}
dict1.update(dict2)
print(dict1)
# 输出:{'apple': 1, 'banana': 2, 'orange': 3, 'pear': 4}

Dictionary filtering

You can use the following methods to filter the dictionary and only keep the key-value pairs that meet the criteria:

my_dict = {
    
    'apple': 1, 'banana': 2, 'orange': 3}
filtered_dict = {
    
    key: value for key, value in my_dict.items() if value > 1}
print(filtered_dict)
# 输出:{'banana': 2, 'orange': 3}

dictionary defaults

If a key doesn't exist in the dictionary, you can set a default value with:

my_dict = {
    
    'apple': 1, 'banana': 2}
print(my_dict.get('orange', 0))
# 输出:0

The above are some advanced usages of Python dictionaries. Dictionaries are a very convenient data structure that is widely used in Python. After mastering the above high-level usage, you can use dictionaries more efficiently and play a greater role in actual development.
The above are the basic usage and examples of Python dictionaries. Hopefully these examples have given you a better understanding of how to use Python dictionaries.

Guess you like

Origin blog.csdn.net/ALiLiLiYa/article/details/130833445