如何在Python中使用for循环创建嵌套字典?

萨拉·金

我正在为我的项目创建youtube下载器,因此我一直在使用YouTube API。我在将数据放入字典中时遇到问题,例如,这是数据:

result = {'kind': 'youtube#searchListResponse', 'etag': '5JMmuS5CVq2hYbanuVXwLKfuwXk', 'nextPageToken': 'CAEQAA', 'regionCode': 'US', 'pageInfo': {'totalResults': 1000000, 'resultsPerPage': 1}, 'items': [{'kind': 'youtube#searchResult', 'etag': '_quYyNz6XPXmAaWfx4pkGm_ZXRA', 'id': {'kind': 'youtube#video', 'videoId': 'Jn09UdSb3aA'}, 'snippet': {'publishedAt': '2020-03-04T12:00:04Z', 'channelId': 'UCyOfqgtsQaM3S-VZnsYnHjQ', 'title': 'The Best of Chopin', 'description': 'Buy the MP3 album on the Official Halidon Music Store:  Listen to our playlist on Spotify: ialClassics Order “100 ...', 'thumbnails': {'default': {'url': 'https://i.ytimg.com/vi/Jn09UdSb3aA/default.jpg', 'width': 120, 'height': 90}, 'medium': {'url': 'https://i.ytimg.com/vi/Jn09UdSb3aA/mqdefault.jpg', 'width': 320, 'height': 180}, 'high': {'url': 'https://i.ytimg.com/vi/Jn09UdSb3aA/hqdefault.jpg', 'width': 480, 'height': 360}}, 'channelTitle': 'HALIDONMUSIC', 'liveBroadcastContent': 'none', 'publishTime': '2020-03-04T12:00:04Z'}}]}

    search = {}
    search_data = []

    for item in result['items']:
        title = item['snippet']['title']
        description = item['snippet']['description']
        video = item['id']['videoId']

        search['title'] = title
        search['description'] = description
        search['videoId'] = video
    
        search_data.append(search)

而且我很难用“标题”作为键将每个数据添加到字典中。所以我希望字典看起来像这样:

{'The Best of Chopin': 
         {'description': 'Buy ... : AYhx Listen .... ', 
          'videoId': 'Jn09UdSb3aA'}, 
'The Next Title': 
         {'description': 'blah blah', 
          'videoId':'121212121'}, 
'The Third one.... and goes on

我已经阅读了很多有关嵌套字典的文章,但是我看到了很多重复的过程,但是却没有如何创建..我尝试并玩了一些,但是却无法完成。我尝试过的唯一接近的解决方案是在for循环中使用“枚举”创建带有键的键,但是我试图使用标题作为键。任何建议将被认真考虑。

贾维斯

像这样做:

search[title] = {}
search[title]['description'] = description
search[title]['videoId'] = video

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在python中使用循环创建元组

如何在python中使用循环创建多个类对象?

如何在Python中创建嵌套字典?

Python如何从嵌套循环返回嵌套字典?

如何在Java中使用嵌套的for循环为矩形图案创建(m)列和(n)行?

如何在嵌套字典中使用.get()?

在Python中使用循环创建交替字典

如何在Python中使用aiohttp或asyncio创建并行循环?

如何在python中使用重复键创建嵌套字典

python-如何在循环中创建字典的字典

在Python中,如何使用for循环从字典创建嵌套列表?

如何在嵌套循环中使用$ _?

如何使用python从XML创建嵌套字典?

如何在Python的嵌套字典中使用相同的键获取所有值?

在python中使用嵌套字典和列表创建json对象

如何在python中使用相同的键组合(附加值)两个嵌套字典?

在python中使用嵌套循环创建表

如何在python中使用docxtpl jinja2标签的字典的嵌套列表

如何创建嵌套字典PYTHON

如何在python中使用多维字典

在Python中使用for循环创建嵌套字典

如何在Ansible中使用嵌套变量(字典键)?

使用for循环在python中创建动态嵌套字典

如何在python中创建嵌套字典

如何在 Python 3 中使用条件解释嵌套字典列表理解

如何在python中使用for循环创建一个新字典

如何在python中使用for循环创建几个pandas框架?

如何在 Python 中使用多个键修改嵌套字典中的一组特定值?

如何在 terraform 中使用嵌套循环