I know I can include Python code from a common file using import MyModuleName
- but how do I go about importing just a dict?
The problem I'm trying to solve is I have a dict that needs to be in a file in an editable location, while the actual script is in another file. The dict might also be edited by hand, by a non-programmer.
script.py
airportName = 'BRISTOL' myAirportCode = airportCode[airportName]
myDict.py
airportCode = {'ABERDEEN': 'ABZ', 'BELFAST INTERNATIONAL': 'BFS', 'BIRMINGHAM INTERNATIONAL': 'BHX', 'BIRMINGHAM INTL': 'BHX', 'BOURNMOUTH': 'BOH', 'BRISTOL': 'BRS'}
How do I access the airportCode
dict from within script.py?
A Dictionary in Python is collection of key-value pairs, where key is always unique and oftenly we need to store a dictionary and read it back again. We can read a dictionary from a file in 3 ways: Using the json. loads() method : Converts the string of valid dictionary into json form.
A Python dictionary is a data structure for storing groups of objects. It consists of a mapping of key-value pairs, where each key is associated with a value. It can contain data with the same or different data types, is unordered, and is mutable.
Just import it
import myDict print myDict.airportCode
or, better
from myDict import airportCode print airportCode
Just be careful to put both scripts on the same directory (or make a python package, a subdir with __init__.py
file; or put the path to script.py on the PYTHONPATH; but these are "advanced options", just put it on the same directory and it'll be fine).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With