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:
JavaScript
x
9
1
test.txt
2
01-01-2020 12:00:00,10
3
01-01-2020 13:00:00,9
4
01-01-2020 14:00:00,8
5
01-01-2020 15:00:00,7
6
01-01-2020 16:00:00,6
7
01-01-2020 17:00:00,5
8
9
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.
JavaScript
1
19
19
1
import flask
2
from flask import request, jsonify
3
4
app = flask.Flask(__name__)
5
app.config["DEBUG"] = True
6
7
@app.route('/', methods=['GET'])
8
def api_data():
9
with open (r"test.txt","r") as f:
10
# d={}
11
l=[]
12
for line in f.read().splitlines()[-5:]:
13
d={}
14
key,val = line.split(",")
15
d[key] = val
16
return d
17
18
app.run()
19
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:
JavaScript
1
12
12
1
def api_data():
2
with open (r"test.txt","r") as f:
3
l=[]
4
for line in f.read().splitlines()[-5:]:
5
key,val = line.split(",")
6
d = {"Date": key, "Value" : val}
7
l.append(d)
8
return l
9
10
res = api_data()
11
print(res)
12
Output:
JavaScript
1
2
1
[{'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'}]
2
Also, you need to append
each object to the list and return the list object; currently you are returning the dictionary object.