繁体   English   中英

从 Python 字典中获取“子”值的最佳方法?

[英]Best method to get “sub” values from Python dictionary?

从 Python dict 读取值的最佳方法是什么?

  • 完整的功能,以及下面包含的字典代码

语境

在做了一些研究之后,似乎 get() 方法 - 应该 - 可以解决问题。 但是,我下面的代码似乎只为"title"键返回“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')}")

我的 Python 代码

#-
# 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 第一个get返回嵌套的词典,或者一个空的字典user丢失,第二get将在返回值title密钥,或None (默认返回值get如果项目缺少)如果没有title密钥。

请注意,如果您使用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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM