Skip to content

Python global dictionary | Example code

  • by

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 the global dictionary value in the function. That’s easy to Modify 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 or suggestions on this Python dictionary tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *