How to read from a text file and store multiple values to a key in dictionary

1256 views python

My text file is of the form:

ABC,_XYZ 45.1976844 -69.458819
AWA,_WES 44.946356 -90.315969
AXA,_WWA 36.3055851 -104.2588701

How do I store this in a dictionary with the letters including ',' and '_' are the keys and the numbers are two different values of that key.

answered question

1 Answer


dicta = dict()
with open("yourfile.txt", "r") as file:
    for i in file:
        line, *lines = i.split()
        dicta[line] = lines

.split() will only split it at the spaces

the dict look like this

{'ABC,_XYZ': ['45.1976844', '-69.458819'], 
'AWA,_WES': ['44.946356', '-90.315969'], 
'AXA,_WWA': ['36.3055851', '-104.2588701']}

here line takes the first value and *lines just takes the rest

posted this

Have an answer?


Please login first before posting an answer.