How to Use a Global Dictionary in Python

Python’s global keyword is used to modify or read global variables inside a function. There are a few specific cases in which this can be beneficial and we will be exploring them in this tutorial.

A global dictionary in Python is just a dictionary defined in the global scope. It can be accessed from anywhere in the code, making it very useful for storing data that needs to be shared among different functions or modules. In this tutorial, we are going to walk you through how to effectively and efficiently use a Global Dictionary in Python.

Step 1. Defining a Global Dictionary

Global dictionaries are defined in the module scope, which is the outermost scope. They can be accessed from anywhere in the code, including inside functions, methods, and classes.

Here’s an example of how to define a global dictionary:

This creates an empty dictionary named global_dict.

Step 2. Modifying the Global Dictionary Inside a Function

If you want to modify the global dictionary within a function, you need to declare the dictionary as global before you modify it. As mentioned, this is done using the global keyword.

This function modifies global_dict by adding a key-value pair to it.

Step 3. Accessing the Global Dictionary

You can access the global dictionary from anywhere in the code, as long as you’re in the same module. This can be inside a function, a method, or even another scope.

Here’s how you can access the global dictionary:

Step 4. Deleting a Key in Global Dictionary

You can delete a key from the global dictionary in the same way you’d delete a key from any other dictionary – using the del keyword.

Here’s how you can delete a key:

Before We Wrap-Up, Let’s Have a Look at the Full Code:

And the Output Would Be as Follows:

{'key': 'value'}

In Conclusion

The use of a global dictionary in Python is a straightforward and robust way to share data among diverse parts of your code.

A word of caution, though. While global variables can be altered and accessed from any part of the code, they should be used sparingly as they can make debugging and code maintenance harder.

It is always suggested to use local variables unless necessary, but in cases where a variable is used across functions, a global variable is indispensable.