Handling the exception with try ... except will solve the issue.
The below program initializes each record with default values of 'None'.
The value will be updated inside the for loop, only if there is no exception (I.E., only if the key is found)
Here is the working example with the exception handling implemented:
# File name: CryptoCompare.py
import pandas as pd
import requests as requests
def get_cryptocompare_data():
url = "https://min-api.cryptocompare.com/data/top/mktcapfull?limit=15&tsym=USD"
data = requests.get(url)
d = data.json()
records = []
for item in d["Data"]:
# Initialize a record with null values
record = {"Type": None, "Name": None, "Supply": None}
try:
# Update values for the available keys
record["Type"] = item["CoinInfo"]["Type"]
record["Name"] = item["CoinInfo"]["Name"]
record["Supply"] = item["RAW"]["USD"]["SUPPLY"]
# Try a key that does not exist
# record["Supply"] = item["abc"]["ijk"]["xyz"]
except KeyError:
# Handle the exception
print("Key not found. Therefore, using the default 'None' value")
# Append record to data set
records.append(record)
df = pd.DataFrame.from_records(records)
# Show all records
print(df)
get_cryptocompare_data()
# End of program
Output (all keys are found):
> python CryptoCompare.py
Type Name Supply
0 1 BTC 1.833352e+07
1 1 ETH 1.105811e+08
2 1 XRP 9.999185e+10
3 1 GAPS 2.000000e+09
4 1 CRO 1.000000e+11
5 1 USDT 4.642367e+09
6 1 BCH 1.838416e+07
7 1 PLF 1.000000e+10
8 1 CTAG 4.000000e+09
9 1 LINK 1.000000e+09
Output (when a key is not found):
> python CryptoCompare.py
Key not found. Therefore, using the default 'None' value
...
Type Name Supply
0 1 BTC None
1 1 ETH None
2 1 XRP None
3 1 GAPS None
4 1 CRO None
5 1 USDT None
6 1 BCH None
7 1 PLF None
8 1 CTAG None
9 1 LINK None