简体   繁体   中英

Read text file and store into dictionary

I am trying to figure out to store content of the file into multiple values in the specific key.

Desired output:

{'city1':[Island-1,Island-3],'city2':[Island-2,Island-4]}

data.txt

city1-south:"London"
city1-south:"Paris"
city1-north:"Amsterdam"
city1-north:"Island-1"
city2-south:"Island-2"
city1-east:"Island-3"
city2-west:"Island-4"


def readFile(data_file):
    data = open(data_file,"r")
    d = {}
    for line in data:
        if 'Island' in line:
            city,loc = line.rstrip("\n").split(":",1)
            d[city] = loc
    print (d)
    data.close()

data_file = "data.txt"
readFile(data_file)

Current output:

{'city2-south': '"Island-2"', 'city2-west': '"Island-4"', 'city1-east': '"Island-3"', 'city1-north': '"Island-1"'}

I can not run your code now because config_file is not defined. I have made some modifications so that your code can run.

with open("data.txt") as data:
    d = {'city1': [], 'city2': []}
    for line in data:
        if 'Island' in line:
            city,loc = line.rstrip("\n").split(":",1)
            for key in d.keys():
                if key in city:
                    d[key].append(loc[1:-1])
print(d)

Results:

{'city1': ['Island-1', 'Island-3'], 'city2': ['Island-2', 'Island-4']}

For now Island-1 etc. can noly be output as string in the dictionary since otherwise python would treat them as variables.

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