0

I have some values, that have been stored as a string in a file.

eg: IDnumber, Name, DOB, address.

Each person has a new line for their info with a comma separating each element.

I have to take this information from the file, and add it to a dictionary, making the ID number a key and the rest the value.

I have tried so many things and am really at the end of my wits.

Can someone please help?

jordanhill123
  • 4,142
  • 2
  • 31
  • 40
tiinkx
  • 13
  • 1
  • 2
  • Take a look at http://stackoverflow.com/questions/4803999/python-file-to-dictionary – AMacK Sep 30 '14 at 01:17
  • will this definitly do multiple values? – tiinkx Sep 30 '14 at 01:30
  • 2
    Can you show us some of the things you have tried? Most people don't want to write your entire program for you, but we'll be glad to answer questions. By seeing what you've tried, we can see if the problem is with a) reading from the file, b) adding it to the dictionary, c) making the ID the key, or d) making the rest the value. – Robᵩ Sep 30 '14 at 01:50

1 Answers1

1

Assuming you have a textfile that consistently looks like this...

001, Joe Smith, 08/10/91, 123 Somewhere dr.
002, Peggy Parker, 01/01/85, 999 Elm St. 
...and so on...

You can build a dictionary with ID as key and the rest as a tuple using something like this:

people = {} 
with open(<file path>) as f:
    for line in f:
        person = line.split(", ")
        people[person[0]] = (person[1], person[2], person[3])

Or keys could also be added to name, DOB, and address:

people = {}
with open(<file path>) as f:
    for line in f:
        items = line.split(", ")
        person = {}
        person['name'] = items[1]
        person['dob'] = items[2]
        person['address'] = items[3]
        people[items[0]] = person
Tanner
  • 430
  • 1
  • 5
  • 12
  • oh my jesus. thank you. you wouldn't believe the rubbish i was writing before. holy christ. now i can actually progress. :D – tiinkx Sep 30 '14 at 04:11