walkman
walkman

Reputation: 498

Python Global Dictionaire how to properly use it between files

Let's simplify and imagine I have this:

#file a.py
import b

 def register(name, value):
     b.mydict[name] = value


#file b.py    
mydict = {}
print(mydict)


#file c.py
import b
print(b.mydict)

File a.py will register some values using the defined function.

File b.py and c.py will print an empty dictionary.

I know this is really a newbie question but...

How do I make it so that when the function registers it updates mydict in the other files as well?

Upvotes: 0

Views: 45

Answers (1)

Anwarvic
Anwarvic

Reputation: 13022

You just need to import this variable from different files. Here is a full example:

  • file1.py:

    my_dict = {"apple": 1, "banana": 2}
    
  • file2.py:

    from file1 import my_dict
    my_dict["carrot"] = 3
    
  • file3.py:

    from file2 import my_dict
    print(my_dict) #{'apple': 1, 'banana': 2, 'carrot': 3}
    

And here is a screenshot on my machine:

Upvotes: 1

Related Questions