I had a dictionary inside the same single python script file. The script worked fine, all right.
I wanted to create an external file that contains the dictionary. Next, I imported the external file (dictionary.py) into the main file (main.py), but the script didn’t work. I would like the import to be successful and without any errors.
This is the external dictionary file (dictionary.py)
class Dict:
def __init__(self):
self.teams = {
"Liverpool": {
"Name": "Liverpool",
"Tournament": "Premier League",
....
This is the main.py file (part of the code). The problem arose when I replaced dict_team (dict_team.items) in place of the previous teams.items(). What is teams? It was the name of the dictionary.
Now I get the error: dict_team = dictionary.Dict (self) NameError: name 'self' is not defined
While if I remove (self), I get the error: AttributeError: 'Dict' object has no attribute 'items'
NOTE: When the dictionary was in the only file and I was using teams.items(), I did not get any errors and the script worked correctly. Teams was the name of the dictionary.
The problem is row: for _team in dict_team.items():
#dictionary
import dictionary
dict_team = dictionary.Dict(self)
#function
def on_tournament_selected(event):
# Clear the entry boxes: aggiunto io
team.delete(0,'end')
req_teams = [] # For all the required teams
sel_tournament = tournament.get() # Get the tournament
# get the names for selected gender
for _team in dict_team.items(): # Go through all the teams in the dictionary
key = _team[0] # Get the key
value = _team[1] # Get the value
if value['Campionato'] == sel_tournament: # If Tournament of the loop-ed team is our selected tourname, then
req_teams.append(key)
team.config(values=req_teams) # Change the values of the combobox
tournament.bind('<<ComboboxSelected>>', on_tournament_selected)
>Solution :
There are a couple of problems:
-
On line 3,
dict_team = dictionary.Dict(self), it doesn’t make sense to writeselfthere.selfis defined only in the class and is used to refer to the current instance. It isn’t used outside a class, so you shouldn’t be passing it there. -
Your
dict_teamis not a dictionary – it’s an instance of a class you’ve created, calledDict. That class doesn’t have anitemsmethod, hence why you get the error. If you just want to use a dict, why are you putting it inside a class in the first place?
If you just want to put your dictionary in another file, then you can, e.g.
sports.py:
teams = {"Liverpool": {...}}
and then you just import and use it wherever you want, e.g.
main.py
from sports import teams
for team, value in teams.items():
# Whatever goes here.