阿晨1998
您可以通过递归找到所有字典。在此之前,我必须澄清以下几点:在字典中查找而d不是在字典中查找b,对吗?如果要查找所有字典,dict示例中有 6 个。如果你想找到所有key-value pairs,它有 9 key-value pairs。所以我有正确的两个版本,一个用于dict,一个用于key-value(仅一行差异):def count_dict(d): if isinstance(d, dict): # count 1 if it is a dict count = 1 # iterate values for dict iterable = d.values() else: count = 0 iterable = d for v in iterable: if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple) or isinstance(v, set): # count recursively count += count_dict(v) return countdef count_dict_pairs(d): if isinstance(d, dict): # count key-value pairs if it is a dict count = len(d) iterable = d.values() else: count = 0 iterable = d for v in iterable: if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple) or isinstance(v, set): count += count_dict(v) return countdef test(): d = { 'a1': { 'a2': [ [1, 2, 3], { 'a3': ({ 'a4': 'cv' }, (1, 2, 3, { 'a5': 'c' })) } ] }, 'b1': { 'b2': [1, 2, 3] }, 3: '3', (1, 2, 3): 'immutable' } print(count_dict(d)) # output 6 print(count_dict_pairs(d)) # output 9希望对你有帮助。