-2

I'm trying to figure out how to read data from a text file line by line. Then, I need to place the data about each member into a dictionary with one key-value pair representing each member. The key is the member number(like 106 below) and the value can list the other three fields..

The data looks like this:

106:Nerk, Fred:fnerk@bigpond.com:0260557642


110:Jones, Sally:sally_jones@internode.com.au:0429765123

Whats the best way of doing this?

4

1 回答 1

0
D = {} #create empty dictionary

for x in open('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'])
#Nerk, Fred
#sally_jones@internode.com.au 
于 2013-10-02T16:22:07.273 回答