Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import or include data structures (e.g. a dict) into a Python file from a separate file

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?

like image 479
Pranab Avatar asked Jan 25 '10 14:01

Pranab


People also ask

Can we import dictionary in Python?

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.

Is dict a data structure in Python?

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.


1 Answers

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).

like image 91
Khelben Avatar answered Sep 24 '22 00:09

Khelben