For loop for reduce duplication?

I’ve created the following code, that pulls Cryptocurrency prices from the CoinGecko api and parses the bits I need in JSON

btc = requests.get("https://api.coingecko.com/api/v3/coins/bitcoin")
btc.raise_for_status()
jsonResponse = btc.json() # print(response.json()) for debug
btc_marketcap=(jsonResponse["market_data"]["market_cap"]["usd"])

This works fine, except I then need to duplicate the above 4 lines for every currency which is getting long/messy & repetitive.

After researching I felt an approach was to store the coins in an array, and loop through the array replacing bitcoin in the above example with each item from the array.

symbols = ["bitcoin", "ethereum", "sushi", "uniswap"]
for x in symbols:
    print(x)

This works as expected, but I’m having issues substituting bitcoin/btc for x successfully.

Any pointers appreciated, and whether this is the best approach for what I am trying to achieve

Answer

Something like this could work. Basically, just put the repeated part inside a function and call it with the changing arguments (currency). The substitution of the currency can be done for example with f-strings:

def get_data(currency):
    btc = requests.get(f"https://api.coingecko.com/api/v3/coins/{currency}")
    btc.raise_for_status()
    return btc.json()["market_data"]["market_cap"]["usd"]
    
for currency in ["bitcoin", "ethereum", "sushi", "uniswap"]:
    print(get_data(currency))