import dictionary from a module

I have been struggling with importing a dictionary from a module I created. I have the module testmodule1.py where I defined the dictionary:

main = {}
main['run_length'] = 1
main['dtt'] = 30
main['nforcing'] = 12

Then on the main script then I import the module and I want to access the value using the key:

import testmodule1
print(testmodule1.main('dtt'))

But I get the error:

Traceback (most recent call last):


File "/Users/gerard/PycharmProjects/BOATSpy/main.py", line 9, in <module>
    print(testmodule1.main('dtt'))
TypeError: 'dict' object is not callable

Any idea on what I'm doing wrong?

Upvotes: 0

Views: 1323

Answers (1)

Cyrlop
Cyrlop

Reputation: 1984

To get the values of a dict from a key, you can either do main['dtt'] (see doc) or main.get('dtt') (see this part of the doc) but not main('dtt') as like the error says, a dict is not callable.

Option 1:

d[key]: Return the item of d with key key. Raises a KeyError if key is not in the map.

Option 2:

d.get(key[, default]): Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

Upvotes: 3

Related Questions