'Print a part of stream-string?
How can I print what's after a colon like 's':, 'E':, or 'p': by giving the symbol as reference? I tried this based on all what I know so far but I get a weird error:
XXXX = f"{{'stream': 'ABCDEF', 'data': {{'s': 'ABC', 'E': 1123, 'p': '0.0', 'q': '0.0'}}}}"
print(XXXX)
print(XXXX['data']['p'])
Output:
{'stream': 'ABCDEF', 'data': {'s': 'ABC', 'E': 1123, 'p': '0.0', 'q': '0.0'}}
Error: in main: print(XXXX['data']['p'])
TypeError: string indices must be integers
Solution 1:[1]
Since XXXX is a string and the example you provided is a json that you want to convert i would sugest the following:
import json
#replace the single quote for double quote in order to parse the json string
x = json.loads(XXXX.replace("'", '"'))
#print the dictionary key you wanted
print(x['data']['p'])
This works as expected for the given input. If you have any other samples that differ from the one provided please let me know.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | M. Villanueva |
