2
\$\begingroup\$

I have the code below which currently pulls pricing data for Ethereum from CoinGecko API. From this request I am building a dictionary that contains the pieces of information and returning it to be used elsewhere in my code.

This function works fine, but I can't help think it could be written so much shorter than this.

How could this be written differently and shorter?

def get_ethereum_data():
    ethereum_data = {}
    response = requests.get(f"{COINGECKO_COIN_URL}")
    response.raise_for_status()
    data = response.json()
    ethereum_data["current_price"] = data["market_data"]["current_price"]["usd"]
    ethereum_data["market_cap"] = data["market_data"]["market_cap"]["usd"]
    ethereum_data["ath"] = data["market_data"]["ath"]["usd"]
    ethereum_data["ath_percentage"] = data["market_data"]["ath_change_percentage"]["usd"]
    ethereum_data["24h_percentage"] = data["market_data"]["price_change_percentage_24h"]
    ethereum_data["7d_percentage"] = data["market_data"]["price_change_percentage_7d"]
    ethereum_data["30d_percentage"] = data["market_data"]["price_change_percentage_30d"]
    ethereum_data["1y_percentage"] = data["market_data"]["price_change_percentage_1y"]
    return ethereum_data
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

You could write a little bit simpler:

  • Inline the returned ethereum_data dictionary, return it directly
  • COINGECKO_COIN_URL is the same as f"{COINGECKO_COIN_URL}" (assuming it's a string)
  • Extract the frequently used data["market_data"] as market_data = data["market_data"]

Like this:

def get_ethereum_data():
    response = requests.get(COINGECKO_COIN_URL)
    response.raise_for_status()

    data = response.json()    
    market_data = data["market_data"]
    
    return {
        "current_price": market_data["current_price"]["usd"],
        "market_cap": market_data["market_cap"]["usd"],
        "ath": market_data["ath"]["usd"],
        "ath_percentage": market_data["ath_change_percentage"]["usd"],
        "24h_percentage": market_data["price_change_percentage_24h"],
        "7d_percentage": market_data["price_change_percentage_7d"],
        "30d_percentage": market_data["price_change_percentage_30d"],
        "1y_percentage": market_data["price_change_percentage_1y"],
    }
\$\endgroup\$
1
  • \$\begingroup\$ Thanks. Yes, this doesn't look as repetitive as what I have written out. Also, good catch on the f string, that must be habit. \$\endgroup\$
    – OrcaDrive
    Sep 24, 2022 at 11:25

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.