Reputation: 1
I have been working on a project and I thought I had an understanding of how to manipulate information in a dictionary into a float to use for comparison however I can see that that is not the case. Any suggestions?
country = "France"
url = 'https://covid-api.mmediagroup.fr/v1/history?country='+country+'&status=confirmed'
print(url)
request = requests.get(url)
dct1 = json.loads(request.text)
key1 = "All"
key2 = "dates"
#datekey = specific date
confirmedcases = []
for datekey in dct1[key1][key2]:
confirmedcases.append(float(dct1[key1][key2][datekey]))
confirmedcases.append(datekey)
confirmedcases.reverse()
print(confirmedcases)
current_high = 0
new_cases = []
for i in range(1,len(confirmedcases)):
new_cases.append(float(confirmedcases[i]) - (float(confirmedcases[i-1])))
if confirmedcases[i] - confirmedcases[i-1] > current_high:
current_high = confirmedcases[i] - confirmedcases[i-1]
dct1 = dct1[i]
print(current_high)
input("press any key")
Upvotes: 0
Views: 66
Reputation: 128
For Comparison, floats may not be that optimal, as it can get bit complicated to handle.
If possible, try to use Integers, if the dataset you receive contains the number of cases. (if any decimal values in them are not significant)
Else, can follow up on this solution to get an idea of how to go about comparisons with floats.
https://stackoverflow.com/a/5595453/8495683
Upvotes: 0
Reputation: 260630
The error raised is :
ValueError Traceback (most recent call last)
<ipython-input-1043-c9ba12594a26> in <module>
22 new_cases = []
23 for i in range(1,len(confirmedcases)):
---> 24 new_cases.append(float(confirmedcases[i]) - (float(confirmedcases[i-1])))
25 if confirmedcases[i] - confirmedcases[i-1] > current_high:
26 current_high = confirmedcases[i] - confirmedcases[i-1]
ValueError: could not convert string to float: '2020-01-22'
Indeed, confirmedcases[i-1]
is '2020-01-22'
that cannot be converted to float.
How did this happen? Let's look at confirmedcases
:
['2020-01-22', 0.0, '2020-01-23', 0.0, '2020-01-24', 2.0, '2020-01-25', 3.0, ...]
This is likely not correct to have mixed the dates and values.
This happened in a previous block:
confirmedcases = []
for datekey in dct1[key1][key2]:
confirmedcases.append(float(dct1[key1][key2][datekey]))
confirmedcases.append(datekey) # why is the date added?
There are other issues in the code, but this gives you a good starting point to debug it.
Upvotes: 2