Skip to content
Advertisement

Creating list of dictionaries from txt using values from for loop

Need to create a list of dictionaries with keys 'Date' and 'Value'. The values of keys are stored in a txt file with following structure:

test.txt
01-01-2020 12:00:00,10
01-01-2020 13:00:00,9
01-01-2020 14:00:00,8
01-01-2020 15:00:00,7
01-01-2020 16:00:00,6
01-01-2020 17:00:00,5
...

The outputs with below code is {"01-01-2020 12:00:00":"10", "01-01-2020 13:00:00":"9"}...

What I would like to do is [{"Date":"01-01-2020 12:00:00","Value":"10"},{"Date":"01-01-2020 13:00:00","Value":"9"}...]

Any help would be much appreciated, thanks.

import flask
from flask import request, jsonify

app = flask.Flask(__name__)
app.config["DEBUG"] = True

@app.route('/', methods=['GET'])
def api_data():
    with open (r"test.txt","r") as f:
        # d={}
        l=[]
        for line in f.read().splitlines()[-5:]:
            d={}
            key,val = line.split(",")
            d[key] = val
        return d
    
app.run()

Advertisement

Answer

Currently, you have created the dictionary object using the date value as the key but if you need the keys to be string Date and Value, you can do the following:

def api_data():
    with open (r"test.txt","r") as f:
        l=[]
        for line in f.read().splitlines()[-5:]:
            key,val = line.split(",")
            d = {"Date": key, "Value" : val}
            l.append(d)
        return l

res = api_data()
print(res)

Output:

[{'Date': '01-01-2020 13:00:00', 'Value': '9'}, {'Date': '01-01-2020 14:00:00', 'Value': '8'}, {'Date': '01-01-2020 15:00:00', 'Value': '7'}, {'Date': '01-01-2020 16:00:00', 'Value': '6'}, {'Date': '01-01-2020 17:00:00', 'Value': '5'}]

Also, you need to append each object to the list and return the list object; currently you are returning the dictionary object.

Advertisement