Python 编写一个算法来计算字典中子字典的数量
我对Python还相当陌生,我正在努力使用嵌套字典。看字典词典:Python 编写一个算法来计算字典中子字典的数量,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我对Python还相当陌生,我正在努力使用嵌套字典。看字典词典: d = { 'a1': { 'a2': [ [1, 2, 3], { 'a3': ({ 'a4': 'cv' }, (1, 2, 3, { 'a5': 'c' })) } ] }, 'b1': { 'b2': [1, 2, 3] }, 3: '3', (1, 2
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'
}
如何计算字典d
中的子目录
我的算法不正确:
def count_dict(d):
# print(d.items())
return sum(1 + count_dict(v) if isinstance(v, dict) else 1 for _, v in d.items())
$> print(count_dict(d))
$> 6
预期结果是9。您可以通过递归找到所有dict。在此之前,我必须澄清以下几点:
d
中查找,而不是在字典b
中查找,对吗dict
。如果要查找所有键值对
,它有9个键值对
dict
,一个计数用于键值
(只有一行差异):
希望能对你有所帮助。我是瞎了还是那本字典里没有“b”?
d
(d
包括在内)里面只有6本字典如果我算对的话是的,我想他指的可能是有多少个键值对,键值对是9@非常感谢,我指的是键值对,我混淆了python字典的概念。
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 count
def 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 count
def 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