4

I get the error name not defined on running this code in python3:

def main(): D = {} #create empty dictionary for x in open('wvtc_data.txt'): key, name, email, record = x.strip().split(':') key = int(key) #convert key from string to integer D[key] = {} #initialize key value with empty dictionary D[key]['name'] = name D[key]['email'] = email D[key]['record'] = record print(D[106]['name']) print(D[110]['email']) main() 

Could you please help me fix this?

1
  • Are you sure the dictionary was populated with key = 106 and 110 ? Commented Oct 10, 2013 at 0:29

1 Answer 1

4

Your variable D is local to the function main, and, naturally, the code outside does not see it (you even try to access it before running main). Do something like

def main(): D = {} #create empty dictionary for x in open('wvtc_data.txt'): key, name, email, record = x.strip().split(':') key = int(key) #convert key from string to integer D[key] = {} #initialize key value with empty dictionary D[key]['name'] = name D[key]['email'] = email D[key]['record'] = record return D D = main() print(D[106]['name']) print(D[110]['email']) 
Sign up to request clarification or add additional context in comments.

5 Comments

how can i make D available so it can be accessed by other functions created in the program?
By returning it from the function, as seen here, and passing it to other functions that need it.
Make it global, that is define it outside all the functions. It will be accessible anywhere from this module (use global if you want to reassign it inside a function).
@Bogdan I can't disagree with that suggestion more. Making global variables in python is rarely the best method... passing the variable around is much clearer and removes difficult to debug scope errors.
It wasn't a suggestion, it was the answer to his question. I agree that having and, especially, changing a global variable is a bad practice most of the time, but we can't really pretend that global variables do not exist in Python. Spaghetti code is one of the things you have to experience before you understand why it's bad.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.