0

I'm learning Python and decided to play around a bit with a project that I've been wanting to tackle for a while now. I ended up trying to use an API that returns data that I would like to write to a CSV file. I'm struggling with how to parse that out given the formatting of the data, though. I used the following lines to grab the data in question. How can I take that data (shortened version shown below the code) and parse that into a CSV file?

    from pycoingecko import CoinGeckoAPI
    import pandas as pd

    cg = CoinGeckoAPI()

    data = cg.get_coin_market_chart_by_id('bitcoin', 'usd', 'max')
    print(data)

{'prices': [[1367107200000, 135.3], [1367193600000, 141.96], [1367280000000, 135.3], [1367366400000, 117.0], [1367452800000, 103.43], [1367539200000, 91.01], [1367625600000, 111.25], [1367712000000, 116.79], [1367798400000, 118.33], [1367884800000, 106.4], [1367971200000, 112.64]]}

2 Answers 2

1

I'd recommend using pandas. Note that in the following snippet just uses the default options for to_csv(), but you can customize it quite a lot to suit your needs.

import pandas as pd
data = {'prices': [[1367107200000, 135.3], [1367193600000, 141.96], [1367280000000, 135.3], [1367366400000, 117.0], [1367452800000, 103.43], [1367539200000, 91.01], [1367625600000, 111.25], [1367712000000, 116.79], [1367798400000, 118.33], [1367884800000, 106.4], [1367971200000, 112.64]]}
df = pd.DataFrame.from_dict(data['prices'])
df.to_csv('test.csv')
Sign up to request clarification or add additional context in comments.

Comments

1

or try something like that:

import csv

a = {'prices': [[1367107200000, 135.3], [1367193600000, 141.96], [1367280000000, 135.3], [1367366400000, 117.0], [1367452800000, 103.43], [1367539200000, 91.01], [1367625600000, 111.25], [1367712000000, 116.79], [1367798400000, 118.33], [1367884800000, 106.4], [1367971200000, 112.64]]}

with open('new_file.csv', 'w+') as f:
    writer = csv.writer(f)
    for line in a.get('prices'):
        writer.writerow(line)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.