[Solved] How to convert txt to dictionary in python [closed]


I’ve added comments to the answer to explain the flow, please add more details in your question if this is not clear enough 🙂

# Open file for reading
file_house_price = open("house_price.txt", "r")

# read all lines from the file into a variable
data_house_price = file_house_price.readlines()

# as we're done with the file, we can safely close it (we have all the data in memory)
file_house_price.close()

# the first line of the data is the column headers separated by comma
# so here we split that line on comma (removing the newline character as well, using replace)
# which gives us a list of strings (each column header)
key_house_price = data_house_price[0].replace("\n","").split(",")

house_price = []

# loop over all the remaining lines from the file (the [1:] gives us all lines, except the first as indexing starts at 0)
for lines in data_house_price[1:]:
    
    # get rid of newline character and split the line on comma
    lines_house_price = lines.replace("\n","").split(",")
    
    # create a dictionary for storing data for this line
    dict_house_price = dict()
    
    # range gives as consecutive numbers from 0 to X-1
    # in this case, all valid indexes for the columns of the current line
    for i in range(len(lines_house_price)):
        
        # store each column value from the line using the column header we got before as key
        dict_house_price[key_house_price[i]] = lines_house_price[i]
    
    # add this lines information to the list of data
    house_price.append(dict_house_price)

# print collected data as output
print(house_price)
# (pretty formatted output):
#
# [{'land': ''},
#  {' building': ' 50',
#   ' distance_to_center': ' 15',
#   ' price': ' 500',
#   'land': '70'},
#  {'land': ''},
#  {' building': ' 60',
#   ' distance_to_center': ' 30',
#   ' price': ' 400',
#   'land': '70'},
#  {'land': ''},
#  {' building': ' 60',
#   ' distance_to_center': ' 55',
#   ' price': ' 300',
#   'land': '70'},
#  {'land': ''},
#  {' building': ' 50',
#   ' distance_to_center': ' 30',
#   ' price': ' 700',
#   'land': '100'},
#  {'land': ''},
#  {' building': ' 70',
#   ' distance_to_center': ' 25',
#   ' price': ' 1000',
#   'land': '100'},
#  {'land': ''},
#  {' building': ' 70',
#   ' distance_to_center': ' 50',
#   ' price': ' 650',
#   'land': '100'},
#  {'land': ''},
#  {' building': ' 100',
#   ' distance_to_center': ' 20',
#   ' price': ' 2000',
#   'land': '120'},
#  {'land': ''},
#  {' building': ' 80',
#   ' distance_to_center': ' 50',
#   ' price': ' 1200',
#   'land': '120'},
#  {'land': ''},
#  {' building': ' 100',
#   ' distance_to_center': ' 50',
#   ' price': ' 1800',
#   'land': '150'},
#  {'land': ''},
#  {' building': ' 90',
#   ' distance_to_center': ' 15',
#   ' price': ' 3000',
#   'land': '150'}]

0

solved How to convert txt to dictionary in python [closed]