【问题标题】:Read a dict of dicts in a list读取列表中的字典
【发布时间】:2013-12-18 18:13:46
【问题描述】:

我想在一个看起来像这样的 json 文件中读取所有 sourceid。 一个id 可以有两个来源,有时是零个来源。

[ 
    {
        "trailers": {
            "quicktime": [], 
            "youtube": [
                {
                    "source": "source1", 
                    "type": "Trailer", 
                    "name": "Vf", 
                    "size": "HD"
                },
        {
                    "source": "source2", 
                    "type": "Trailer", 
                    "name": "Vf", 
                    "size": "HD"
                }
            ], 
            "id": 57417
        }, 

    {
        "trailers": {
            "quicktime": [], 
            "youtube": [], 
            "id": 57418
        }
] 

我尝试了很多解决方案,我停在了这个,它也不起作用:

from itertools import chain
trailers = {}
for item in j:        
    if item['trailers']:
        e = item['trailers']
        for k,value in e.iteritems():
            if k == "youtube":
                for each_dict in value:
                    for innerk, innerv in each_dict.iteritems():
                        if innerk == "source" :
                            trailers = dict(trailers.items() , {'trailer' : 'None'}.iteritems())                                                                
                        else:
                            trailers = {'trailer' : 'None'}

编辑: 我想看看这个结果:

57417, source1, source2
57418, None

你有什么建议吗?

【问题讨论】:

  • 你想达到什么目的?找到 YouTube 上的所有预告片?
  • 你期望什么输出?
  • 嗯...你考虑过import json吗?
  • 我想看到的输出是:57417, source1, source2 ans 57418, None 当然我导入了json,除了这部分之外一切正常。
  • 你在描述你想要什么时有点含糊。我有一种预感,您的问题可能与here 提出的问题相似。

标签: python json list python-2.7 dictionary


【解决方案1】:

在 YouTube 上查找所有预告片:

trailers = {film['trailers']['id']: [source['source'] for source in film['trailers'].get('youtube', [])] 
            for film in j}

这会产生:

>>> {film['trailers']['id']: [source['source'] for source in film['trailers'].get('youtube', [])] 
...             for film in j}
{57417: ['source1', 'source2'], 57418: []}

【讨论】:

  • @SteveJessop:那里有嵌套列表理解。但是我首先在什么是列表和什么是字典上绊倒了。现在一切正常。
猜你喜欢
  • 1970-01-01
  • 2022-11-28
  • 2015-12-24
  • 1970-01-01
  • 2015-09-23
  • 2022-01-02
  • 2013-08-22
  • 1970-01-01
  • 2018-08-27
相关资源
最近更新 更多