python - 使用嵌套列表计算字典中特定项目的数量
问题描述
我有一个包含以下多个值的字典:
{'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)?
解决方案
我认为最简单的方法是递归搜索字典:
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
推荐阅读
- sql-server - 来自 SQL Server 的 pandas read_sql_table() 问题
- javascript - Discord.js 从 voiceStateUpdate 获取用户 ID
- pine-script - 您如何在 Pinescript 上将 RSI 与布林带策略相结合
- android - 如何从服务执行深层链接
- python - ValueError:使用 plt.show() 时第 0 年超出范围
- swift - 在 OSX 应用程序中未调用 didRegisterForRemoteNotificationsWithDeviceToken 方法
- hibernate - Spring DataJPA @ManyToOne 单向 N+1 问题
- maven - 有没有办法使用 REST API 获取 TeamCity 中所有 Maven settings.xml 文件的列表?
- postgresql - pod重启后emptyDir卷不为空?
- reactjs - 如何通过打字稿在forwardRef中建议自动完成