首页 > 解决方案 > 使用嵌套列表计算字典中特定项目的数量

问题描述

我有一个包含以下多个值的字典:

{'ads': None, 'results': [{'height': 1112, 'image': 'https://www.ucsfhealth.org/-/media/project/ucsf/ucsf-health/medical-tests/hero/coombs-test-direct-2x.jpg', 'source': 'Bing'},{'ads': None, 'results': [{'height': 1132, 'image': 'https://news.images.itv.com/image/file/2164058/img.jpg', 'source': 'Bing'},'ads': None, 'results': [{'height': 1112, 'image': 'http://s1.ibtimes.com/sites/www.ibtimes.com/files/2016/11/11/hiv-test.jpg', 'source': 'Bing'}

如果我想简单地计算字典中存在多少“图像”值,那么最有效的方法是什么(例如,在上面的示例中,我希望输出报告为 3)?

标签: pythondictionaryelementcounting

解决方案


我认为最简单的方法是递归搜索字典:

def count(my_collection, my_key):
    # Start the count
    total = 0
    
    # If it is a list or a tuple, use a different counting method
    if isinstance(my_collection, list) \
            or isinstance(my_collection, tuple):

        for item in my_collection:
            if item == my_key:
                total += 1
            else:
                total += count(item, my_key)

    elif isinstance(my_collection, dict):
        if my_key in my_collection:
            total += 1
        for item in my_collection.values():
            total += count(item, my_key)

    return total


my_dict = {'image': 1, 4: [{'image': 1}, {'not_image': 2, 'a': {'image': 1}}]}
print(count(my_dict, 'image'))
>>> 3

它的工作方式:

  • 它计算一个键在你的 dict/list/tuple 中的次数
  • 它检查该字典/列表/元组中的所有字典/列表/元组
  • 重复步骤 1

推荐阅读