0

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)
  • I need to test your understanding first, so that I can make proper sense of the question: when you write `class Dict:`, what do you think that means? What do you think a class is, and what do you think is its purpose? Where the code says `dictionary.Dict(self)`, what exactly do you want that to do? (Regardless of what your thought process is - the problem has nothing to do with `import` or modules or separate files, and everything to do with classes and how to use them.) – Karl Knechtel Jul 05 '22 at 04:44
  • @Karl Knechtel I had used the class to group and sort the dictionary code, but I can safely delete the class. Where the code says "dictionary.Dict (self)", I would just like to import the dictionary from the external file. I want to import it to be able to use it in the function, precisely in the line: for _team in dict_team.items (). Can you show me what code I should use? I would appreciate very much. Thank you –  Jul 05 '22 at 04:48
  • I added a link for a duplicate question. I know it says that it's about how to `import` the file, but the examples also show how to use the module after importing. – Karl Knechtel Jul 05 '22 at 05:14
  • Out of curiosity, why did you think you needed a class in the first place? – ndc85430 Jul 06 '22 at 06:39

2 Answers2

1

There are a couple of problems:

  1. On line 3, dict_team = dictionary.Dict(self), it doesn't make sense to write self there. self is 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.

  2. Your dict_team is not a dictionary - it's an instance of a class you've created, called Dict. That class doesn't have an items method, 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.
ndc85430
  • 1,395
  • 3
  • 11
  • 17
  • Ok, I take off self as per your first suggestion. Yes, I just want to use a dict, so do I have to remove the class? I will have to import the file by typing: diz_sq = dictionary_squadre ()? After, in the function, write: dictionary_squadre.items ()? I think not. Could you show me the code please? Thank you –  Jul 05 '22 at 04:32
  • You don't need a class at all if you want a dictionary. You said the code was working before you introduced the class, so what was the problem with it? – ndc85430 Jul 05 '22 at 04:33
  • The code worked when there was only one single file, so the dictionary was in the one file along with the function. The problem arose when I created a second external file exclusively for the dictionary. How can I import it correctly? (deleting the class) –  Jul 05 '22 at 04:36
  • As usual: if your dictionary is called `teams` in a module called `sports`, for example, you'd just write `from sports import teams`. – ndc85430 Jul 05 '22 at 04:38
  • I know this. I meant to say 2 things: this dict_team = dictionary.Dict () and then the line for _team in dict_team.items (). How should I write here? –  Jul 05 '22 at 04:41
  • dict_team = teams() and dict_team.items()? –  Jul 05 '22 at 04:42
  • I think you're confused. I don't know why you want a _function_ now. I've edited my post with some code. – ndc85430 Jul 05 '22 at 04:47
0

I had used the class to group and sort the dictionary code, but I can safely delete the class.

It seems that by "the dictionary code", you mean the code that creates the ordinary, underlying Python dict. Classes do not exist for this grouping/organizing purpose - modules do. Classes have nothing to do with it. (They can be used that way, but it's usually abusive.)

If you want your module dictionary to contain a dict named teams, then simply write the corresponding dictionary.py file to use a global variable:

# dictionary.py
teams = {
    "Liverpool": {
        "Name": "Liverpool",
        "Tournament": "Premier League",
        # ...
    }
}

Then after you import the module, that dict is an attribute of the module, which you can access with plain old . syntax:

# main.py
import dictionary
# we access `teams` from the `dictionary` module, and then `items()` from that
for team in dictionary.teams.items():
    ...

Alternately, you can use from import syntax to use the name directly:

from dictionary import teams
for team in teams.items():
    ...
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153