What is the best way to read values from a Python dict?
Context
After doing some research it appears as though the get() method -should- do the trick.
However, my code below only ever seems to return "None" for the "title"
key.
I highly suspect that I need to go into the sub-dictionary/key-value-pairs, but I'm not quite sure what that would look like.
This solution is -close- to what I'm trying to do, except I want the strings, not the indexes. https://stackoverflow.com/a/47107021/6779209
This is another similar question which seems to come close:
Accessing values from Python sub-dictionary
When I try to add title = [user['title'] for user in data]
to my function I get an error: TypeError: string indices must be integers
I can certainly try adding a for
loop but I question whether or not that is overkill.
This is the specific line where I am trying to print additional values.
print(f"{user} is streaming {data.get('title')}")
My Python Code
#-
# Check status against JSON file
# This also set the keys on a per-user basis
#
def processJSON():
with open('channel_data.json', 'r') as file:
lines = file.readlines()
channel_json = json.loads("".join(lines))
data = {}
for element in channel_json['data']:
data[element['user_login']] = element
#-
# Determine if the user is online or not
for user in streamers:
if user in data.keys():
print(f"{user} is streaming {data.get('title')}")
else:
print(f"{user} is offline :(")
# print( json.dumps(data, indent=3) )
# End processJSON()
processJSON()
Sample Dictionary (created using json.dumps() for debugging)
{
"dutchf0x": {
"user_login": "dutchf0x",
"user_name": "DuctchF0x",
"game_name": "Monopoly Plus",
"title": "nobody loses friendships with this game",
"viewer_count": 24773,
"started_at": "2021-07-07T16:59:08Z",
"thumbnail_url": "https://static-cdn.jtvnw.net/previews-ttv/live_user_philza-{width}x{height}.jpg",
"is_mature": false
},
"libertyranger": {
"user_login": "libertyranger",
"user_name": "libertyranger",
"game_name": "Science \\u0026 Technology",
"title": "Streaming UFO Cam - Background Audio is Copyright FREE, 1920s through 1960s Sci-Fi Radio Theater",
"viewer_count": 1,
"started_at": "2021-07-06T12:52:25Z",
"thumbnail_url": "https://static-cdn.jtvnw.net/previews-ttv/live_user_libertyranger-{width}x{height}.jpg",
"is_mature": false
}
}
In this case data
has two layers. you first need to get your streamer.
Try:
data[user]['title']