#๐Ÿ”’ Trouble dealing with yaml dictionaries in python. Error is

75 messages ยท Page 1 of 1 (latest)

halcyon night
#

string indices must be integers but I swear I am typecasting it right. Here is the code.


    try:
        with open('config.yaml', "r") as file:
            data = yaml.safe_load(file) or {}  # If file is empty, return an empty dictionary
    except FileNotFoundError:
        data = {}

    print(wallet)  # Debugging linemy_address = wallet['address']

    data["wallet"] = myAddr
    data["wallet"]["tokens"] += tokens

    with open("config.yaml", 'w') as file:  
        yaml.dump(data, file, default_flow_style=False)
        
    print(f"Tokens saved to {config.yaml}")

def myWalletTokens(my_address):
    url = f"https://api.etherscan.io/api?module=account&action=tokentx&address={my_address}&apikey={config.get_apis().get('etherscan')}"
    response = requests.get(url).json()

    tokens = set()

    if response["status"] == "1":  # Success
        for tx in response["result"]:
            tokens.add(tx["contractAddress"])  # Collect unique token contract addresses

    print("Tokens found in wallet:", tokens)

    tokens_list = list(tokens)
    
    updateWalletConfig(my_address, tokens_list)```

here is the yaml file structure

```wallet:
  address: "aaa"  # Replace with your wallet address
  private_key: "aaa"  # Replace with your wallet private key
  tokens:
    - "0xTokenAddress1"
    - "0xTokenAddress2"

Please help!

craggy stormBOT
#

Hey @halcyon night!

Please edit your message to use a code block

Add a py after the three backticks.

```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
craggy stormBOT
#

@halcyon night

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

fast mortar
#

could you add syntax highlighting according to instructions the bot mentioned?

halcyon night
#

yes sorry

#
def updateWalletConfig(myAddr, tokens):

    try:
        with open('config.yaml', "r") as file:
            data = yaml.safe_load(file) or {}  # If file is empty, return an empty dictionary
    except FileNotFoundError:
        data = {}

    print(wallet)  # Debugging linemy_address = wallet['address']

    data["wallet"] = myAddr
    data["wallet"]["tokens"] += tokens

    with open("config.yaml", 'w') as file:  
        yaml.dump(data, file, default_flow_style=False)
        
    print(f"Tokens saved to {config.yaml}")

def myWalletTokens(my_address):
    url = f"https://api.etherscan.io/api?module=account&action=tokentx&address={my_address}&apikey={config.get_apis().get('etherscan')}"
    response = requests.get(url).json()

    tokens = set()

    if response["status"] == "1":  # Success
        for tx in response["result"]:
            tokens.add(tx["contractAddress"])  # Collect unique token contract addresses

    print("Tokens found in wallet:", tokens)

    tokens_list = list(tokens)
    
    updateWalletConfig(my_address, tokens_list)```
royal condor
#

what is the full traceback?

halcyon night
#

wallet:
  address: "aaa"  # Replace with your wallet address
  private_key: "aaa"  # Replace with your wallet private key
  tokens:
    - "0xTokenAddress1"
    - "0xTokenAddress2"```
fast mortar
#

yeah post the traceback

halcyon night
#

how do i get that

royal condor
#

!traceback

halcyon night
#

i made it catch the error

craggy stormBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

royal condor
#

^ post the entirety of this kind of error

fast mortar
#

make it...not catch the error?

halcyon night
#

ok hold on

#

data["wallet"]["tokens"] += tokens
TypeError: string indices must be integers

royal condor
#

yea, if there is another try/catch we don't see, that might prevent you from actually seeing the full error.

halcyon night
#

File "c:\Users\e7illice\Documents\python3\tradebot\tradebot.py", line 370, in <module>
asyncio.run(main())
File "C:\Users\e7illice\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\e7illice\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "c:\Users\e7illice\Documents\python3\tradebot\tradebot.py", line 367, in main
await asyncio.gather(scan_mempool(), monitor_sales())
File "c:\Users\e7illice\Documents\python3\tradebot\tradebot.py", line 158, in monitor_sales
myWalletTokens(my_address)
File "c:\Users\e7illice\Documents\python3\tradebot\tradebot.py", line 305, in myWalletTokens
updateWalletConfig(my_address, tokens_list)
File "c:\Users\e7illice\Documents\python3\tradebot\tradebot.py", line 283, in updateWalletConfig
data["wallet"]["tokens"] += tokens

fast mortar
#

what's tokens here?

royal condor
#

I would assume that myAddr is not actually a dictionary then

halcyon night
#

ooo

fast mortar
#

did you at least check that the types of the variables were what you expected?

royal condor
#

did you mean to do:
data["wallet"]["address"] = myAddr
perhaps?

halcyon night
#

yes that might be the problem

#

you guys are right im messing up some vars here i just couldnt see it

fast mortar
#

if I were debugging such an error, checking the contents of the variables would be the first thing I'd do

#

to make sure they match my assumptions

halcyon night
#

now its raising a key error for wallet

#

but my yaml has wallet in it right there

#

File "c:\Users\e7illice\Documents\python3\tradebot\tradebot.py", line 284, in updateWalletConfig
data["wallet"]["address"] = myAddr
KeyError: 'wallet'

fast mortar
#

I'm sure you already checked the contents of data...right?

halcyon night
#

it gives me this

fast mortar
#

uh, that makes no sense

#

what did you use to print data?

halcyon night
#

hold up

#
try:
        with open('config.yaml', "r") as file:
            data = yaml.safe_load(file) or {}  # If file is empty, return an empty dictionary
    except FileNotFoundError:
        data = {}
    
    print(data)
    print(wallet)  # Debugging linemy_address = wallet['address']

    data["wallet"]["address"] = myAddr
#

{}
{'address': 'aaa', 'private_key': 'a', 'tokens': ['0xTokenAddress1', '0xTokenAddress2']}

#

then

#

key error

fast mortar
#

so is data that first empty dict?

halcyon night
#

i guess but then how is it reading wallet

#

OOOOO

#

omg

#

im fried

#

jesus dont let me program anything

#

O wait its still giving me a key error ok nvm

fast mortar
#

given that the dict is empty, I'm sure that's expected?

halcyon night
#

ok i changed the code so the wallet does return content

#

but its still gives me key error ill show output

#
def updateWalletConfig(myAddr, tokens):
    
    print(wallet)  # Debugging linemy_address = wallet['address']

    print(wallet["wallet"]["address"])
    print(wallet["wallet"]["tokens"])

    wallet["wallet"]["address"] = myAddr
    wallet["wallet"]["tokens"] += tokens

    with open(config(configPath), 'w') as file:  
        yaml.dump(wallet, file, default_flow_style=False)
        
    print(f"Tokens saved to {config.yaml}")```
#

{'address': 'aaa', 'private_key': 'aaa', 'tokens': ['0xTokenAddress1', '0xTokenAddress2']}

fast mortar
#

but the key error relates to data not wallet

#

so how is changing the wallet going to help?

halcyon night
#

na i removed data entirely because i made two vars of the same thing

#

wallet = config.get_wallet()

fast mortar
#

ok so you cannot figure out why wallet does not have a particular key?

halcyon night
#

na because like when i print(wallet) it gives me this = {'address': 'aaa', 'private_key': 'aaa', 'tokens': ['0xTokenAddress1', '0xTokenAddress2']}

#

so why cant

#

i iterate

#

throug hit

fast mortar
#

where do you see the wallet key?

halcyon night
#

in the config its here yaml wallet: address: "a" # Replace with your wallet address private_key: "a" # Replace with your wallet private key tokens: - "0xTokenAddress1" - "0xTokenAddress2"

fast mortar
#

you yourself just gave me the printed output of wallet, and it does not have a key named wallet

halcyon night
#

ohhh

#

ok

#

yes

#

my fault

fast mortar
#

ok so where is the confusion coming from now?

halcyon night
#

i think i understand more now if i edit this code rq it shouldnt give me the error 1 sec

#

yes i fixed that error and got another one

#

we are making progress

#

โค๏ธ

craggy stormBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.