我有一个字典列表,我需要从列表中的每个字典中提取特定的关键字。
字典列表如下所示:
[{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'}]我该怎么做才能把所有的“name”键都取出来呢?
发布于 2014-07-24 08:26:08
解决方案很简单:
for elem in list:
print elem['name']发布于 2014-07-24 08:31:40
要获取所有名称的列表,您可以使用列表理解:
>>> 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']https://stackoverflow.com/questions/24923090
复制相似问题