AutomaticStatic
AutomaticStatic

Reputation: 1739

Access dictionary module items

my working folder is /scripts/

I created a file that contains only a dictionary

my_dict = {'sky' : 'blue'}

Within that file, I can print my_dict['sky'] just fine.

In PyCharm I created a new folder within /scripts/ called /scripts/dictionaries/. Inside there I have a file called dictionary_file.py, inside of which is my_dict.

It seems PyCharm auto generated a dictionaries module. I can from dictionaries import my_dict fine but then why I try to do my_dict['sky'] I get:

TypeError: 'module' object has no attribute '__getitem__'

I'm sure this is a dumb noob question, but I'm stuck. Thanks in advance for you help.

Upvotes: 1

Views: 1633

Answers (1)

DevLounge
DevLounge

Reputation: 8447

from dictionaries.dictionary_file import myDict

print myDict['sky']

will for sure throw: TypeError: 'module' object has no attribute '__getitem__' because Python thinks that myDict is a module object in this case

from dictionaries import dictionary_file

print dictionary_file.myDict['sky']

Now Python knows that the module dictionary_file of the package dictionaries has something called myDict and discovers on runtime that myDict is a dict which has a __getitem__ method implemented.

Anytime you try to access a dictionary value via its key, python called the __getitem__ method of the dict class.

You can also do

from dictionaries.dictionary_file import *

print myDict['sky']

Upvotes: 5

Related Questions