user11004079
user11004079

Reputation:

Read text file of titles into dictionary

I have this text file of destinations and I need to read them into a dictionary and sort them out based on the starting place and destination.

JFK MCO
ORD DEN
ORD HOU
DFW PHX
JFK ATL
ORD DFW
ORD PHX
ATL HOU
DEN PHX
PHX LAX
JFK ORD
DEN LAS
DFW HOU
ORD ATL
LAS LAX
ATL MCO
HOU MCO
LAS PHX
STL PDX

Expected Results:

{'JKF' : {'MCO', 'ATL','ORD'}, 'ORD' : {'DEN' , 'HOU' , 'DFW' , 'PHX' , 'ATL' ........}}

The main ideas is that the starting place is on the left and the destination is on the right. Group the destinations to each starting place.

Upvotes: 1

Views: 59

Answers (3)

Jab
Jab

Reputation: 27495

This is done very easily using very basic for loop and a dictdefaultdict

from collections import defaultdict
d = defaultdict(set)
with open("filename.txt", "r") as f:
    for line in f: 
        start, place = line.split()
        d[start].add(place)

It can also be done using the csv module

from collections import defaultdict
import csv

d = defaultdict(set)
with open("filename.txt", "r") as f:
    r = csv.reader(f, delimiter=' ')
    for start, place in r: d[start].add(place)

Of course, this results in a defaultdict, although you can still use it the same as a dict, if you want d to be a true dict after use d = dict(d).

Upvotes: 3

billydh
billydh

Reputation: 1035

try this

depart_place = ['JFK', 'ORD', 'ORD', 'DFW', 'JFK']
destination = ['MCO', 'DEN', 'HOU', 'PHX', 'ATL']

place_dict = {}

for place, dest in zip(depart_place, destination):
    if place in place_dict:
        place_dict[place].add(dest)
    else:
        place_dict[place] = {dest}

So, essentially, we are iterating through tuples of departing place and destination (place, dest) resulting from zip(depart_place, destination). Then, we check if the place is already in the dictionary, we append the destination to it or else, we create a new key-value pair for the place

Upvotes: 1

blhsing
blhsing

Reputation: 106658

You can iterate through the lines, split the lines and use dict.setdefault to store the destinations into a dict of sets with the originating place as the keys:

d = {}
with open('file.txt') as file:
    for line in file:
        orig, dest = line.split()
        d.setdefault(orig, set()).add(dest)

d becomes:

{'JFK': {'ORD', 'ATL', 'MCO'}, 'ORD': {'DEN', 'HOU', 'ATL', 'DFW', 'PHX'}, 'DFW': {'PHX', 'HOU'}, 'ATL': {'MCO', 'HOU'}, 'DEN': {'PHX', 'LAS'}, 'PHX': {'LAX'}, 'LAS': {'PHX', 'LAX'}, 'HOU': {'MCO'}, 'STL': {'PDX'}}

Upvotes: 3

Related Questions