0

So there's a few partial answers to this here, but nothing clearly answers this question.

I want to take a .txt file with an arbitrary number of names, each on a new line, like this.

John Citizen
Genghis Khan
Ex Parrot
... could be hundreds of names

Then I want to create a new instance of this Friend() object

class Friend(object):
    def __init__(self, name):
        self.name = name
        self.somequality = "somequality"

    def somemethod(self):
        return self.somequality

for each line in the text file.


Currently I have this code:

friends_dict = {}
with open('NameList.txt') as f:
    friend_list = [line.strip() for line in f]
friend_instance_list = []
for i in friend_list:
    friend_instance_list.append(Friend(i))
friends_dict = dict(zip(friend_list, friend_instance_list))     

And this works, it makes a dictionary of instances, paired with the strings they represent. I can even call their names like this:

print(friends_dict["John Citizen"].name)

Is this actually the best way to do things? It seems really clumsy and annoying not to have any of these objects assigned to variables. It makes dealing with them a real pain, but I don't have any idea how to go about assigning these instances from the dictionary to variables.

Community
  • 1
  • 1
  • 1
    When I run exactly this code, it works—`thevariable` gets the value `'somequality'`, just as you'd want it to. So, are you sure this is the same as your actual code? – abarnert Apr 20 '15 at 07:21
  • As a side note, the same way you did `friend_list = [line.strip() for line in f]`, you can do `friend_instance_list = [Friend(i) for i in friend_list]`. Or, even better, just go right to `friends_dict = {i: Friend(i) for i in friend_list}` and don't even bother with the `friend_instance_list`. – abarnert Apr 20 '15 at 07:22
  • Meanwhile: Your link was broken. I guessed that you meant the first page that comes up when you search SO for that text, rather than the text itself interpreted as a URL, but you might want to check to make sure I got it right. More importantly: in what way are those answers "partial"? What part of the question do they not answer? – abarnert Apr 20 '15 at 07:26
  • 1
    It's working for me too, the only way it wouldnt work is if 'def somemethod' is not idented/defined correctly – lapinkoira Apr 20 '15 at 07:28
  • I've edited this question because I found the answer to my problem (it was stupid, related to trying to save the dictionary using pickle). – Pez Picacious Apr 20 '15 at 07:33
  • have you tried `friends_dict[u'John Citizen']`? Maybe it's a charset issue... – Finwood Apr 20 '15 at 07:33

0 Answers0