Python global dictionary | Example code

Use the global keyword in the dictionary when you want to change the value in Python. If the dictionary is defined outside function then by default it has global scope.

Python global dictionary example

Simple example code change global dictionary value in the function. That’s easy to Modifying a global dictionary in python within a function.

Note: To assign to a global variable from a function you need to use a global directive. Otherwise, Python will create a local variable with the same name instead.

dic1 = {'a': 1, 'b': 2}


def func():
    global dic1
    dic1['a'] = 100


print(dic1)
func()
print('New Dictionary ', dic1)

Output:

Python global dictionary

How to make a dictionary created in a function visible to the outside in Python?

Answer: Just put global in front of the variable, and conditionally instantiate it.

class Test(object):

    def create_dict():
        global my_dict
        if 'my_dict' not in globals():
            my_dict = {'a': 1, 'b': 2}

    create_dict()
    print(my_dict)

Output: {‘a’: 1, ‘b’: 2}

Do comment if you have any doubts and suggestions on this Python dictionary tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.