【问题标题】:Python - How to get a specific value from a large list of dicts?Python - 如何从大量字典中获取特定值?
【发布时间】:2021-06-29 12:02:28
【问题描述】:

我有一个很大的字典列表,但我只想要字典列表中的特定信息。

如何从这个 dict 列表中获取 key standard: ('standard': {'width': 640, 'height': 480, 'url': 'the url here'}) 的值?

{'snippet': {'videoOwnerChannelId': 'UCG8rbF3g2AMX70yOd8vqIZg', 'channelTitle': 'Logan Paul', 'videoOwnerChannelTitle': 'Logan Paul', 'playlistId': 'PLH3cBjRCyTTxIGl0JpLjJ1vm60S6oenaa', 'description': 'Join the movement. Be a Maverick ► https://ShopLoganPaul.com/\nIn front of everybody...\nSUBSCRIBE FOR DAILY VLOGS! ►\nWatch Previous Vlog ► https://youtu.be/kOGkeS4Jbkg\n\nADD ME ON:\nINSTAGRAM: https://www.instagram.com/LoganPaul/\nTWITTER: https://twitter.com/LoganPaul\n\nI’m a 23 year old manchild living in Los Angeles. This is my life.\nhttps://www.youtube.com/LoganPaulVlogs', 'channelId': 'UCG8rbF3g2AMX70yOd8vqIZg', 'title': 'THE MOST EMBARRASSING MOMENT OF MY LIFE - CHOCH TALES EP. 5', 'resourceId': {'videoId': 'ft6FthsVWaY', 'kind': 'youtube#video'}, 'thumbnails': {'medium': {'width': 320, 'height': 180, 'url': 'https://i.ytimg.com/vi/ft6FthsVWaY/mqdefault.jpg'}, 'standard': {'width': 640, 'height': 480, 'url': 'https://i.ytimg.com/vi/ft6FthsVWaY/sddefault.jpg'}, 'high': {'width': 480, 'height': 360, 'url': 'https://i.ytimg.com/vi/ft6FthsVWaY/hqdefault.jpg'}, 'default': {'width': 120, 'height': 90, 'url': 'https://i.ytimg.com/vi/ft6FthsVWaY/default.jpg'}, 'maxres': {'width': 1280, 'height': 720, 'url': 'https://i.ytimg.com/vi/ft6FthsVWaY/maxresdefault.jpg'}}, 'position': 4, 'publishedAt': '2019-03-19T02:00:20Z'}, 'id': 'UExIM2NCalJDeVRUeElHbDBKcExqSjF2bTYwUzZvZW5hYS4wOTA3OTZBNzVEMTUzOTMy', 'etag': 'UU0sUEMm-gC0bcXTF9v1pFV9ZJY', 'kind': 'youtube#playlistItem'}

【问题讨论】:

  • 我不明白...你想获取什么信息?
  • 字典缩略图中的信息>>标准
  • 你的意思是print(d["snippet"]["thumbnails"]["standard"]) 吗?
  • @AndrejKesely 是的

标签: python list dictionary for-loop


【解决方案1】:

在您的示例中,您没有字典列表,即[{},{},...],而是嵌套字典。如果您确定所有键都必须存在,您可以按如下方式访问该值:

std_thumb = myDict['snippet']['thumbnails']['standard']
width = std_thum['width']
height = std_thum['height']
url = std_thum['url']

如果您确定所有嵌套字典中只有一个名为“标准”的键,则以下内容也适用,取自 Get all keys of a nested dictionary:

def recursive_items(dictionary):
    for key, value in dictionary.items():
        if type(value) is dict:
            yield from recursive_items(value)
        else:
            yield (key, value)

for key, val in recursive_items(myDict):
    if key == 'standard':
        print(f'Key: {key}')
        print(f'Val: {val}')

如果这些键始终位于嵌套的顶层,Ahmadreza 的答案当然是合适的,但在您的示例中并非如此。我的第一个示例是索引字典的标准方法,第二个示例是递归查找键。

附:你不需要if 'standard' in eachDict.keys(),你可以简单地调用if standard in eachDict,因为“in”关键字已经只引用了键。

附言您可能会发现使用 json 库可视化复杂字典很有用;以下将为您缩进:

import json
print(json.dumps(myDict, indent=4))

【讨论】:

  • 我得到了错误 --> std_thum = OurList['sn-p']['thumbnails']['standard'] TypeError: list indices must be integers or slices, not str
  • 这意味着在字典上调用,因此 myDict[key1][key2] 等。如果它是一个列表,你可以说“std_thumb_list = [d['sn-p'][' thumbnails']['standard'] for d in list_of_dicts]
【解决方案2】:

假设您的字典位于数据变量中...

  • 如果您只需要一次提取这些数据,您可以使用:
data['snippet']['thumbnails']['standard']
  • 否则你可以使用这个:
for item in data:
    if item == 'snippet':
        for information in data[item]:
            if information == "thumbnails":
                print(data[item][information]['standard'])

>>> Output 
{'width': 640, 'height': 480, 'url': 'https://i.ytimg.com/vi/ft6FthsVWaY/sddefault.jpg'}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    • 2017-01-05
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    相关资源
    最近更新 更多