使用嵌套列表计算字典中特定项目的数量

Counting number of a particular item in a dictionary with a nested list

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

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

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

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

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
  • 中出现的次数
  • 它会检查 dict/list/tuple
  • 中的所有 dicts/lists/tuples
  • 重复步骤 1