I have a nested dictionary:
d = {'key': 1, 'lock':{'key': 3, 'lock': {'key': 7, 'lock': None}}}
and I am hoping to simply get the number of times 'key' occurs. So in this example, the output would be:
3
because 'key' appears 3 times. I know this is pretty straight forward but I'm a bit foggy on how to do this with dictionaries. I would prefer to not use any libraries if possible.
Thanks for the help!
You can use a function that recursively counts the given key:
def count(d, k):
c = int(k in d)
for v in d.values():
if isinstance(v, dict):
c += count(v, k)
return c
or to write the above in a more concise way:
def count(d, k):
return (k in d) + sum(count(v, k) for v in d.values() if isinstance(v, dict))
so that count(d, 'key')
returns: 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.