Count nested dictionary keys and values

Sometimes you need to get count of keys and values in dictionary

Count nested dictionary keys and values
1 min read
By prox

Sometimes you need to get count of keys and values in dictionary. You obviously can do this by using len(dict), but it will only return key count for first dictionary level.

To count keys and values in nested dictionary, you can use this function. It also correctly works with list and tuple values.

def count_k_v(d):
    keys = 0
    values = 0
    if type(d) == dict:
        for item in d.keys():
            if isinstance(d[item], (list, tuple, dict)):
                keys += 1
                k, v = count_k_v(d[item])
                values += v
                keys += k
            else:
                keys += 1
                values += 1

    elif type(d) == list or type(d) == tuple:
        for item in d:
            if isinstance(item, (list, tuple, dict)):
                k, v = count_k_v(item)
                values += v
                keys += k
            else:
                values += 1

    return keys, values

Example

Lets take this sample dictionary and specify it as an argument for a function:

d = {
      'quack':
              {
                'zozo': '10',
                'pysha': 'queeee',
              },
      'bobique': ['iaiaia', '12312', 'auasuhrh1r'],
      'put-in': 123,
      'fofof':
              {
                  'qwijhg': ['123', 13248, 'asd8ghg'],
                  'wijfr':
                            {
                              'quwhf': '128u4',
                              'hg': 2835,
                            },
              },
      'ghuh': (982, 'sygf'),
}
k, v = count_k_v(d)
print(f"Found {k} keys and {v} values")

>>> Found 11 keys and 13 values