【问题标题】:How to get certain keys from a list of dictionaries?如何从字典列表中获取某些键?
【发布时间】:2014-07-24 00:09:29
【问题描述】:

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

字典列表如下所示:

[{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'}]

我将如何从那里取出所有“名称”键?

【问题讨论】:

    标签: list python-2.7 dictionary


    【解决方案1】:

    解决方法很简单:

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

    【讨论】:

    • +1 给你 - 通常在做任何事情之前添加一个检查键是否在元素中是明智的。
    【解决方案2】:

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

    >>> 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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 2020-12-29
      • 2022-08-19
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多