如何从词典列表中获取某些键?

时间:2014-07-24 00:09:30

标签: list python-2.7 dictionary

我有一个字典列表,我需要从列表中的每个字典中提取某些键。

词典列表如下:

[{u'api_detail_url': u'http://www.giantbomb.com/api/platform/3045-94/', u'abbreviation': u'PC', u'site_detail_url': u'http://www.giantbomb.com/pc/3045-94/', u'id': 94, u'name': u'PC'}, {u'api_detail_url': u'http://www.giantbomb.com/api/platform/3045-35/', u'abbreviation': u'PS3', u'site_detail_url': u'http://www.giantbomb.com/playstation-3/3045-35/', u'id': 35, u'name': u'PlayStation 3'}, {u'api_detail_url': u'http://www.giantbomb.com/api/platform/3045-20/', u'abbreviation': u'X360', u'site_detail_url': u'http://www.giantbomb.com/xbox-360/3045-20/', u'id': 20, u'name': u'Xbox 360'}, {u'api_detail_url': u'http://www.giantbomb.com/api/platform/3045-86/', u'abbreviation': u'XBGS', u'site_detail_url': u'http://www.giantbomb.com/xbox-360-games-store/3045-86/', u'id': 86, u'name': u'Xbox 360 Games Store'}]

如何从那里获取所有“名称”密钥?

2 个答案:

答案 0 :(得分:2)

解决方案很简单:

for elem in list:
    print elem['name']

答案 1 :(得分:0)

要获取所有名称的列表,您可以使用列表解析:

>>> L = [{u'api_detail_url': u'http://www.giantbomb.com/api/platform/3045-94/', u'abbreviation': u'PC', u'site_detail_url': u'http://www.giantbomb.com/pc/3045-94/', u'id': 94, u'name': u'PC'}, {u'api_detail_url': u'http://www.giantbomb.com/api/platform/3045-35/', u'abbreviation': u'PS3', u'site_detail_url': u'http://www.giantbomb.com/playstation-3/3045-35/', u'id': 35, u'name': u'PlayStation 3'}, {u'api_detail_url': u'http://www.giantbomb.com/api/platform/3045-20/', u'abbreviation': u'X360', u'site_detail_url': u'http://www.giantbomb.com/xbox-360/3045-20/', u'id': 20, u'name': u'Xbox 360'}, {u'api_detail_url': u'http://www.giantbomb.com/api/platform/3045-86/', u'abbreviation': u'XBGS', u'site_detail_url': u'http://www.giantbomb.com/xbox-360-games-store/3045-86/', u'id': 86, u'name': u'Xbox 360 Games Store'}]
>>> [D['name'] for D in L]
['PC', 'PlayStation 3', 'Xbox 360', 'Xbox 360 Games Store']

如果name不在每个字典中,您可以过滤字典:

>>> [D['name'] for D in L if 'name' in D]
['PC', 'PlayStation 3', 'Xbox 360', 'Xbox 360 Games Store']