从Python字典中读取值的最佳方法是什么?
- 功能完整,下面包含字典代码
上下文
在做了一些研究之后,似乎get()方法应该能做到这一点。然而,我下面的代码似乎只返回& None">
我高度怀疑我需要进入子字典/键-值对,但我不非常确定那会是什么样子。
这个解决方案是-接近-我想做的,除了我想要的字符串,而不是索引。https://stackoverflow.com/a/47107021/6779209
这是另一个类似的问题,似乎接近:访问Python子字典中的值当我尝试将title = [user['title'] for user in data]
添加到我的函数时,我得到一个错误:TypeError: string indices must be integers
我当然可以尝试添加一个for
循环,但我怀疑这是否过分。
这是我试图打印附加值的特定行。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()
示例字典(使用json.dumps()创建用于调试)
{
"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
}
}
在这种情况下,data
有两层。你首先需要得到你的飘带。
试题:
data[user]['title']
最好的惯用方法是:
data.get(user, {}).get("title")
如果缺少用户或用户的title
,则返回None
。如果缺少"title"
0,第一个get
将返回嵌套字典或空字典,如果没有title
键,第二个get
将返回title
键处的值,或者None
(如果缺少get
项,则返回CC_14的默认返回值)。
注意,如果你使用data[user]
语法,如果user
不存在于你的字典中,它将抛出一个异常。这可能是首选,但如果不是,请使用get
。
使用@not-spesuhl和@conmak的建议,这个更新版本让我前进:)
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[user].get('title')}")
print( data.get("title") )
else:
print(f"{user} is offline :(")
# print( json.dumps(data, indent=3) )
# End processJSON()
processJSON()