tiinkx tiinkx - 1 year ago 63
Python Question

Python - taking a string from file, converting to list, adding to dictionary wth multiple values

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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download