Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing and editing a dictionary from multiple files

Can dictionaries be accessed by multiple files in Python 2.7?
One can import classes and functions from other files, but can the same be done with dictionaries?
I might have a file with a dictionary and an assortment of functions that can be used by other files to do things with the dictionary, but is it necessary to write a function for every single thing I might want to do? I would like to be able to do basic things, like printing part of the dictionary, from another file.
Essentially, what I want to know is: Does importing a file also import a dictionary within the file and if not, how can I?

If this is possible, I would also like to know if the original dictionary can be edited from another file. As well as printing part of it, could I then change a value in the original dictionary?

I have been unable to find anything about this on the internet. Please educate me, stackoverflow.

like image 914
Erebus9997 Avatar asked Dec 05 '25 17:12

Erebus9997


2 Answers

Yes, dictionaries are not special and can be imported into other modules, just like anything else you define in a Python module. Like functions and classes, dictionaries are Python objects, and importing does nothing but create a new reference in the current module to values you imported.

You can manipulate the dictionary from anywhere; dictionaries are mutable structures, once you have a reference to it you can alter the keys and values of that dictionary.

like image 176
Martijn Pieters Avatar answered Dec 08 '25 08:12

Martijn Pieters


file1.py

d = {'a':5}

file2.py

from file1 import d
d['a'] += 3
def whatever():
   pass

file3.py

from file2 import whatever
from file1 import d
print d
#now if you wanted the unmodified value from file1 you could reload it
import file1
reload(file1)
from file1 import d
print d  #note only in this file is d reverted ... any other place would have the modified dictionary
like image 26
Joran Beasley Avatar answered Dec 08 '25 09:12

Joran Beasley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!