The issue in your code arises from the nested loops you are using to iterate over bet.items(). Specifically, you have two nested for-loops that both iterate through dictionaries, but they don't have any conditions to exit properly, which can lead to the printing or input being handled multiple times for certain conditions.
Here's a breakdown of the relevant portion of your code:
for k, v in bet.items():
if k.lower() == 'currentaltcoinbalances':
for k, v in v.items():
if v != 0:
print(f"Balance type: {k.upper()} | Amount: {amount} | Type: {betType} | Balance: {v} | Timestamp: {timestamp}")
- The first loop iterates over every key-value pair in the
bet dictionary.
- Inside this loop, if the key is
'currentAltCoinBalances', it enters the second loop, which iterates over each key-value pair in the nested dictionary v.
- If any of those values (
v from currentAltCoinBalances) is not equal to 0, it prints the formatted string with that balance information.
The main issue is that if currentAltCoinBalances is not a key in bet, it falls into the else statement, which uses input() that will be executed for each key-value pair in bet. Thus, if bet contains multiple keys, it shows the input prompt that many times.
Proposed Solution
To prevent printing or asking for input with every iteration, you should structure your code like this:
- Perform the check for
currentAltCoinBalances first, and only loop once based on its presence.
- Use a flag to determine whether you need to print the initial balance info based on whether the
currentAltCoinBalances key exists.
Here’s a modified version of your code:
for bet in bets['data']:
timestamp = bet['timestamp']
balanceType = bet['balanceType']
amount = bet['amount']
betType = bet['type']
if 'currentAltCoinBalances' in bet:
for k, v in bet['currentAltCoinBalances'].items():
if v != 0:
print(f"Balance type: {k.upper()} | Amount: {amount} | Type: {betType} | Balance: {v} | Timestamp: {timestamp}")
else:
print(f"Balance type: {balanceType.upper()} | Amount: {amount} | Type: {betType} | Balance: {bet['currentBalance']} | Timestamp: {timestamp}")
In this code:
- We use an
if statement to check for the existence of currentAltCoinBalances before deciding which block of code to execute.
- If that key exists, we handle the balances in that dictionary. Otherwise, we fall back to printing the general balance information.
This way, each piece of information is printed at most once per bet entry.