SoFunction
Updated on 2025-04-11

Detailed explanation of how to build a global dictionary in Python

In Python programming, global variables refer to variables that can be accessed throughout the entire program run. As a special global variable, the global dictionary can store various types of data, including strings, numbers, lists, tuples, etc., which makes it very useful in data management and cross-module communication. This article will provide a detailed introduction to how to build and use a global dictionary in Python, including a theoretical overview and code examples.

1. Theoretical Overview

  • Definition and scope of global variables
    • Global variables: Variables defined outside the function are called global variables. Global variables can be accessed and modified throughout the program.
    • Scope: The scope of a variable determines the scope of accessibility of a variable in the program. The scope of a global variable is the entire program, while the scope of a local variable is limited to the functions or code blocks that define it.
  • The concept of global dictionary
    • dictionary: The dictionary in Python is a mutable container model that can store objects of any type, such as integers, strings, etc. Each element of the dictionary is a key-value pair, and the values ​​are accessed through keys.
    • Global Dictionary: The dictionary defined in the global scope is the global dictionary. It can be accessed and modified throughout the program and is suitable for storing and managing global data.
  • Pros and cons of using global dictionaries
    • advantage:
      • Easy to communicate across modules and share data.
      • Easy to manage and maintain global data.
      • Supports dynamic addition and deletion of key-value pairs.
    • shortcoming:
      • May cause naming conflicts and data inconsistencies.
      • Excessive use of global variables can make the code difficult to maintain and debug.

2. Steps to build a global dictionary

Define global dictionary

Define a dictionary variable in the global scope of the program.

Using global dictionary in functions

When accessing and modifying global dictionaries in functions, you need to useglobalKeyword declarations to avoid creating local variables with the same name.

Using global dictionaries across modules

If you need to share a global dictionary between multiple modules, you can define the dictionary in a separate module and then import the module in other modules to access the global dictionary.

3. Code examples

Here is a detailed code example showing how to build and use a global dictionary in Python.

# 1. Define a global dictionary# Define a dictionary named global_dict in the global scopeglobal_dict = {}
 
# 2. Use global dictionary in functionsdef add_to_global_dict(key, value):
    global global_dict  # Declare global variables using global keywords    global_dict[key] = value  # Add key-value pairs to the global dictionary 
def remove_from_global_dict(key):
    global global_dict  # Declare global variables using global keywords    if key in global_dict:
        del global_dict[key]  # Remove key-value pairs from global dictionary 
def update_global_dict(key, value):
    global global_dict  # Declare global variables using global keywords    if key in global_dict:
        global_dict[key] = value  # Update key-value pairs in the global dictionary    else:
        add_to_global_dict(key, value)  # If the key does not exist, add a new key-value pair 
def print_global_dict():
    # Print the contents of the global dictionary    for key, value in global_dict.items():
        print(f"{key}: {value}")
 
# 3. Use global dictionary across modules# Create a module named to store the global dictionaryThe content of # is as follows:# global_config_dict = {}
 
# Import modules in the main program and use the global dictionary in it# import config
# config.global_config_dict['setting1'] = 'value1'
# print(config.global_config_dict)
 
# To simplify the example, the use of global dictionary is demonstrated directly in the main program. 
# 4. Sample Programif __name__ == "__main__":
    # Add key-value pairs to the global dictionary    add_to_global_dict('name', 'Alice')
    add_to_global_dict('age', 30)
    
    # Update key-value pairs in the global dictionary    update_global_dict('age', 31)
    
    # Print the contents of the global dictionary    print("Global Dictionary after adding and updating:")
    print_global_dict()
    
    # Delete key-value pairs in the global dictionary    remove_from_global_dict('age')
    
    # Print the contents of the global dictionary    print("Global Dictionary after removing a key-value pair:")
    print_global_dict()

4. Detailed explanation of the code

Define global dictionary

global_dict = {}

Define a global scope calledglobal_dictempty dictionary.

Using global dictionary in functions

def add_to_global_dict(key, value):
    global global_dict  # Declare global variables using global keywords    global_dict[key] = value  # Add key-value pairs to the global dictionary

add_to_global_dictThe function accepts two parameters:keyandvalueand to the global dictionaryglobal_dictAdd a key-value pair to it. Used inside a functionglobalKeyword Statementglobal_dictBe a global variable to avoid creating local variables with the same name.

Similarly,remove_from_global_dictFunctions are used to delete a key-value pair from the global dictionary.update_global_dictFunctions are used to update key-value pairs in the global dictionary (update the value if the key exists, otherwise add new key-value pairs).

Print global dictionary

def print_global_dict():
    # Print the contents of the global dictionary    for key, value in global_dict.items():
        print(f"{key}: {value}")

print_global_dictFunctions are used to print the contents of a global dictionary. It iterates over key-value pairs in the global dictionary and prints each key-value pair.

Use global dictionary across modules (optional)

In practical applications, it may be necessary to define a global dictionary in a separate module for sharing among multiple modules. Here is how to create a name calledThe module to store the global dictionary and import the module in the main program to use the global dictionary. However, to simplify the example, the use of global dictionary is demonstrated here directly in the main program.

Sample program

if __name__ == "__main__":
    # Add key-value pairs to the global dictionary    add_to_global_dict('name', 'Alice')
    add_to_global_dict('age', 30)
    
    # Update key-value pairs in the global dictionary    update_global_dict('age', 31)
    
    # Print the contents of the global dictionary    print("Global Dictionary after adding and updating:")
    print_global_dict()
    
    # Delete key-value pairs in the global dictionary    remove_from_global_dict('age')
    
    # Print the contents of the global dictionary    print("Global Dictionary after removing a key-value pair:")
    print_global_dict()

In the example program, we first add some key-value pairs to the global dictionary, then update one, and finally delete one. After each operation, we print the contents of the global dictionary to verify that the operation is successful.

5. How to use global dictionary

In Python, the use of global dictionary involves several key steps: defining a global dictionary, declaring a reference to the global dictionary in a function (usingglobalKeyword), read and write the global dictionary inside the function. The following are detailed explanations and examples of these steps.

1. Define the global dictionary

First, define a global dictionary in the global scope (usually the top level of the module). This is usually done at the beginning of a Python file.

# Define a global dictionary in a global scopeglobal_data = {}

2. Declare global dictionary in function

When you want to modify the global dictionary inside the function, you need to use it inside the functionglobalThe keywords declare that you are referring to the dictionary in the global scope, rather than creating a local variable with the same name.

def modify_global_data(key, value):
    global global_data  # Declare what we want to use is global_data in the global scope    global_data[key] = value  # Modify the global dictionary

3. Read and write global dictionary

Once you declare a global dictionary inside the function, you can read and write it like you would a normal dictionary.

def read_global_data(key):
    global global_data  # Although we only read and not write in this function, it is a good habit to declare global (although not required)    return global_data.get(key, "Key not found")  # Use the get method to avoid KeyError 
# Example: Modify and read global dictionarymodify_global_data('name', 'Alice')
print(read_global_data('name'))  # Output: Aliceprint(read_global_data('age'))   # Output: Key not found

Things to note

  • Avoid naming conflicts: Ensure that the name of the global dictionary does not conflict with local variables or other global variables inside the function.
  • Thread safety: In a multithreaded environment, access to the global dictionary may require a synchronization mechanism to avoid race conditions.
  • Code readability: In large projects, excessive use of global variables may reduce the readability and maintainability of the code. Consider using other data structures (such as classes, module properties) or design patterns (such as singleton patterns) to manage global state.
  • Sharing among modules: If you want to share a global dictionary between multiple modules, you can define it in a separate module and import the module if needed.

4. Example: Use global dictionary across modules

Suppose we have a name calledmodule, which defines a global dictionarysettings

# 
settings = {}

Then, in another module, we can importconfigModule and access or modifysettingsdictionary.

# 
import config
 
# Modify the global dictionary['debug_mode'] = True
 
# Read global dictionaryprint(['debug_mode'])  # Output: True

In this way, we can share and modify global dictionaries between different modules. However, be aware that this practice may introduce dependencies and complexity and should be used with caution in large projects.

In short, global dictionaries are a powerful tool in Python, but they also need to be used with caution to avoid potential problems. By following best practices and considerations, you can effectively leverage global dictionaries to manage global state and data sharing.

6. Conclusion

Global dictionary is a very useful data structure in Python programming, which can be used to store and manage global data, implement cross-module communication and data sharing. However, excessive use of global variables can make the code difficult to maintain and debug. Therefore, when using global dictionaries, it is necessary to carefully consider their advantages and disadvantages, and to design and use them reasonably according to actual needs. Through this article's introduction and sample code, readers should be able to master how to build and use global dictionaries in Python.

This is the end of this article about how to build a global dictionary in Python. For more related content on building a global dictionary in Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!