Turning text in a text file to lists in a dictionary

so for example i had a text file with peoples phone numbers,name,address. that looked like this with a return at the end of each line

555-667282,bill higs,67 hilltop

555-328382,john paul,85 big road

555-457645,zac fry,45 tony's rd

555-457645,kim fry,45 tony's rd

and i wanted to put it all in a dictionary and in the dictionary the phone number was the key and there name and address was a list. so if i wanted to print the dictionary it would look something like this. what would be the code to do this

{555-667282: ['bill higs','67 hilltop'], 555-328382: ['john paul','85 big road'], 555-457645: ['zac fry','45 tony's rd'],['kim fry','45 tony's rd']}

Answers


dicto = {}

with open('your_file.txt') as f:
    for line in f:
        s_line = line.rstrip().split(',')
        dicto[s_line[0]] = s_line[1:]

Edit:

To handle cases where there are multiple entries associated with one phone number:

from collections import defaultdict

dicto = defaultdict(list)

with open('your_file.txt') as f:
    for line in f:
        s_line = line.rstrip().split(',')
        dicto[s_line[0]].append(s_line[1:])

This file format is what the csv module in the standard library was designed to handle. However you can't have a dictionary laid-out the way you want because a dictionary key can only map to one thing. A simple way to work around that limitation is to map each phone number to a list of lists, as shown in the sample code and output below:

import csv

result = {}
with open('numbers.txt', 'rb') as input:
    for phone_number, name, address in csv.reader(input):
        if phone_number in result:
            result[phone_number] += [[name, address]]
        else:
            result[phone_number] = [[name, address]]

print result

Output:

{'555-328382': [['john paul', '85 big road']], 
 '555-457645': [['zac fry', "45 tony's rd"], ['kim fry', "45 tony's rd"]], 
 '555-667282': [['bill higs', '67 hilltop']]}

The code within the inner for loop can be simplified by using another standard library class called defaultdict which is a subclass of dict. They automatically initialize dictionary entries to a specified default value whenever a non-existent one's value is referenced. Here's how one could be applied to this example:

import collections
import csv

result = collections.defaultdict(list)
with open('numbers.txt', 'rb') as input:
    for phone_number, name, address in csv.reader(input):
        result[phone_number] += [[name, address]]

print result

Output of second version:

defaultdict(<type 'list'>, {
 '555-328382': [['john paul', '85 big road']],
 '555-457645': [['zac fry', "45 tony's rd"], ['kim fry', "45 tony's rd"]],
 '555-667282': [['bill higs', '67 hilltop']]})

defaultdict objects can otherwise be used just like a regular dictionary by the rest of your code.


Need Your Help

Serializing Exception to be throwable

c# .net exception serialization

While I realize there is a similar question (How to serialize an Exception object in C#?), and though the answers on that page were helpful, they didn't exactly solve the problem or answer the ques...