简体   繁体   中英

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.

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'}}

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) .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM