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

7

54

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?

Airwoman answered 25/1, 2010 at 14:41 Comment(0)
M
81

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

Maurer answered 25/1, 2010 at 14:48 Comment(0)
G
16

Assuming your import myDict works, you need to do the following:

from myDict import airportCode
Greengrocer answered 25/1, 2010 at 14:44 Comment(0)
B
2

Well, it doesn't need to be a .py file. You could just do:

eval(open("myDict").read())

It's a gaping security hole, though.

Another module you might want to look at is csv for importing CSV files. Then your users could edit it with a spreadsheet and you don't have to teach them Python syntax.

Bezonian answered 25/1, 2010 at 14:46 Comment(2)
How is calling eval on the contents of a file any more of a "gaping security hole" than importing it?Aretha
Because import does all its work in the namespace of the module being imported, but eval() can do anything. Not much of a practical difference; they're both pretty dangerous.Bezonian
H
2

When you perform an import in python you are really just pulling in names into your current namespace. It does not really matter what those names refer to so:

from myDict import airportCode

Will work regardless of whether airportCode is a function, class or just a field as in your case.

Hamlett answered 25/1, 2010 at 15:19 Comment(0)
L
1

If your dict has to be hand-editable by a non-programmer, perhaps it might make more sense using a CSV file for this. Then you editor can even use Excel.

So you can use:

import csv
csvfile = csv.reader(open("airports.csv"))
airportCode = dict(csvfile)

to read a CSV file like

"ABERDEEN","ABZ"
"BELFAST INTERNATIONAL","BFS"
"BIRMINGHAM INTERNATIONAL","BHX"
"BIRMINGHAM INTL","BHX"
"BOURNMOUTH","BOH"
"BRISTOL","BRS"

Careful: If an airport were in that list twice, the last occurrence would silently "overwrite" any previous one(s).

Lorrinelorry answered 25/1, 2010 at 14:51 Comment(2)
Actually, if you create a dict with the same key twice, the second instance will silently overwrite the first >>> d = {1:2, 2:4, 1:3.5} >>> d {1: 3.5, 2: 4}Assuasive
I'm surprised no one's suggested JSON. It's pretty easy to use JSON in Python, and the data structure looks much like (but not exactly the same as) Python's.Fiery
K
0
from myDict import airportCode
airportNode = 'BRISTOL'
myAirportCode = airportCode[airportName]

If myDict should get accessed from a Python module in a different directory, you have to provide a __init__.py module.

For more Information about this topic have a look at the module chapter of the Python documentation.

Ketone answered 25/1, 2010 at 14:48 Comment(0)
G
0

Use csv. Stick import csv with the rest of your module imports, and then you can do as follows:

f = open('somefile.csv')
reader = csv.DictReader(f, (airport, iatacode))
for row in reader:
   print row

which should give you a list of dictionaries:

airport | iatacode
__________________
Aberdeen| ABZ

to create the csv file:

f = open('somefile.csv', 'w')
writer = csv.DictWriter(f, (airport, iatacode))
for row in airportcode:
   writer.writerow()
f.close()

which will create a csv file with airports and IATA TLAs in two columns with airport and iatacode as the headers.

You can also skip the dicts and just have strings by using Reader and Writer rather than DictReader and DictWriter.

By default, the csv module produces excel-style csv, but you can set whatever dialect you like as a kwarg.

Geer answered 25/1, 2010 at 16:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.