Search code examples
pythonpython-3.xdictionarytypeerrortraceback

Extracting values from a dictionary by key, string indices must be integers


I'm trying to extract values from dictionary recieved with websocket-client via key and for some reason it throws me an error "String indices must be integers". no matter how im trying to do it im constantly getting the same error unless i'm writing it as lines of code then it works, unfotunately that's not what I'm after...

Example:

ws = websocket.WebSocket()
ws.connect("websocket link")

info = ws.recv()
print(info["c"])

ws.close()

Output:

Traceback (most recent call last):
  File "C:\Python\project\venv\example\example.py", line 14, in <mod
ule>
    print(info["c"])
TypeError: string indices must be integers

While if im taking the same dictionary and writing it down suddenly it works...

Example:

example = {"a":"hello","b":123,"c":"whatever"}
print(example["c"])

Output:

whatever

Any help is appreciated, thanks!

SOLUTION

firstly you have to import the websocket and json module as you receive dictionary json object and then you have to load that json objects.

import websocket
import json

ws = websocket.WebSocket()
ws.connect("websocket link")

info = json.loads(ws.recv())
print(info["c"])

ws.close()

Solution

  • Likely the dictionary you receive from the web socket is a json object:

    import websocket
    import json
    
    ws = websocket.WebSocket()
    ws.connect("websocket link")
    
    info = json.loads(ws.recv())
    print(info["c"])
    
    ws.close()