从字典中提取数据

时间:2019-03-19 20:46:24

标签: python list dictionary

这是我正在处理的数据的示例。

{'etag': '"ld9biNPKjAjgjV7EZ4EKeEGrhao/1v2mrzYSYG6onNLt2qTj13hkQZk"',
 'items': [{'etag': '"ld9biNPKjAjgjV7EZ4EKeEGrhao/Xy1mB4_yLrHy_BmKmPBggty2mZQ"',
            'id': '1',
            'kind': 'youtube#videoCategory',
            'snippet': {'assignable': True,
                        'channelId': 'UCBR8-60-B28hp2BmDPdntcQ',
                        'title': 'Film & Animation'}},
           {'etag': '"ld9biNPKjAjgjV7EZ4EKeEGrhao/UZ1oLIIz2dxIhO45ZTFR3a3NyTA"',
            'id': '2',
            'kind': 'youtube#videoCategory',
            'snippet': {'assignable': True,
                        'channelId': 'UCBR8-60-B28hp2BmDPdntcQ',
                        'title': 'Autos & Vehicles'}},
           {'etag': '"ld9biNPKjAjgjV7EZ4EKeEGrhao/nqRIq97-xe5XRZTxbknKFVe5Lmg"',
            'id': '10',
            'kind': 'youtube#videoCategory',
            'snippet': {'assignable': True,
                        'channelId': 'UCBR8-60-B28hp2BmDPdntcQ',
                        'title': 'Music'}},
 'kind': 'youtube#videoCategoryListResponse'}

我想提取2列数据

  1. 'id'
  2. “标题”

也就是说,从第一项开始,我会有'id' = 1, 'title' = Film & Animation

我是Python的新手,用Python做到这一点的最佳方法是什么?

非常感谢大家!

3 个答案:

答案 0 :(得分:0)

我认为是

for it in data['items']:
  print(it['id'], it['snippet']['title'])

答案 1 :(得分:0)

'items'是可以通过for循环遍历对象的列表:

false

答案 2 :(得分:0)

猜猜有一个错字'items'是一个list,每当我们将方括号([)开始时,都需要将其关闭(])。

{'etag': '"ld9biNPKjAjgjV7EZ4EKeEGrhao/1v2mrzYSYG6onNLt2qTj13hkQZk"',
 'items': [{'etag': '"ld9biNPKjAjgjV7EZ4EKeEGrhao/Xy1mB4_yLrHy_BmKmPBggty2mZQ"',
            'id': '1',
            'kind': 'youtube#videoCategory',
            'snippet': {'assignable': True,
                        'channelId': 'UCBR8-60-B28hp2BmDPdntcQ',
                        'title': 'Film & Animation'}},
           {'etag': '"ld9biNPKjAjgjV7EZ4EKeEGrhao/UZ1oLIIz2dxIhO45ZTFR3a3NyTA"',
            'id': '2',
            'kind': 'youtube#videoCategory',
            'snippet': {'assignable': True,
                        'channelId': 'UCBR8-60-B28hp2BmDPdntcQ',
                        'title': 'Autos & Vehicles'}},
           {'etag': '"ld9biNPKjAjgjV7EZ4EKeEGrhao/nqRIq97-xe5XRZTxbknKFVe5Lmg"',
            'id': '10',
            'kind': 'youtube#videoCategory',
            'snippet': {'assignable': True,
                        'channelId': 'UCBR8-60-B28hp2BmDPdntcQ',
                        'title': 'Music'}},     # <-----  HERE, no brackets
 'kind': 'youtube#videoCategoryListResponse'}

列表理解

# all items
[row for row in data['items']]   

# custom data from all items
[(row['id'], row['snippet']['title']) for row in data['items']]     

# just id > 0 (filtering data)
[row for row in data['items'] if row['id']>0]   

结合使用两种过滤数据提取特殊字段:

[(r['id'], r['snippet']['title']) for r in data['items'] if r['id'] > 0]   

还要给filter一个机会

这真的很酷

f = lambda r: (r['id'], r['snippet']['title'])
result = filter(f, data['items'])
相关问题