Moez
(Moez)
#1
Hi guys,
I tried to create a csv file from an API object response but I faced this error:
Traceback (most recent call last):
File "stockprice.py", line 59, in <module>
writer.writerows(zip(k, v))
TypeError: 'float' object is not iterable
The response is below:
{'stock_symbol': 'AAPL', 'percentage_change': -3.7328, 'current_price': 156.8, 'last_close_price': 162.88}
my code to create a csv file is:
for k, v in reponse.items():
with open('test.csv', 'w') as f:
writer = csv.writer(f, delimiter=',')
writer.writerows(zip(k, v))
I tried to round the float values but I had the issue with multiple values data types here.
do you have an idea please guys
writer.writerows(zip([k], [v]))
Moez
(Moez)
#3
The desired result is:
stock_symbol,percentage_change,current_price,last_close_price
AAPL, -3.7, 156.8, 162.8
now I don’t have any errors but I have a different result:
last_close_price,162.88
with open('test.csv', 'w') as f:
writer = csv.writer(f, delimiter=',')
[writer.writerows(zip([k], [v])) for k, v in response.items()]
or
(lambda x, y: writer.writerows(zip(x, y)))(response.keys(), response.values())
or
(lambda x: writer.writerows(x))(response.items())
but it will give you,
stock_symbol,AAPL
percentage_change,-3.7328
current_price,156.8
last_close_price,162.88
which can be done by simple.
writer.writerows(response.items())
Moez
(Moez)
#5
thank you @vainaixr this solves my issue, but I was wondering how to display all keys in one line and values in the next one
with open('test.csv', 'w') as f:
f.write(', '.join(response.keys()))
f.write('\n')
f.write(', '.join(f'{x}' for x in response.values()))
1 Like
Moez
(Moez)
#7
Thank you a lot @vainaixr 