More Pythonic way of counting things in a heavily nested defaultdict

0 votes

My code currently has to count things in a heavily nested dict into another. I have items that need to be indexed by 3 values and then counted. So, before my loop, I initialize a nested defaultdict like:

from collections import defaultdict

type_to_count_dic = defaultdict(
        lambda: defaultdict(
            lambda: defaultdict(int)
        )
    )

Which allows me to count the items within a tight loop like so:

for a in ...:
    for b in ...:
        for c in ...:
            type_to_count_dic[a][b][c] += 1

Can anyone help me with a more idiomatic/Pythonic way of doing something like this?

Jun 20 in Python by ana1504.k
• 7,870 points
20 views

1 answer to this question.

0 votes

You can try the following, this might help you:

from collections import defaultdict

class _defaultdict(defaultdict):
    def __add__(self, other):
        return other

def CountTree():
    return _defaultdict(CountTree)

>>> t = CountTree()
>>> t['a']
defaultdict(<function CountTree at 0x9e5c3ac>, {})
>>> t['a']['b']['c'] += 1
>>> print t['a']['b']['c']
1
answered Jun 20 by SDeb
• 13,160 points

Related Questions In Python

0 votes
1 answer

Is there a way of using .lower more effectively in tkinter?

Here is a simple function and some ...READ MORE

answered Sep 25, 2018 in Python by Priyaj
• 56,900 points
156 views
0 votes
1 answer

Replace First and Last Word of String in the Most Pythonic Way

import re a = " this is a ...READ MORE

answered Aug 22, 2018 in Python by ariaholic
• 7,340 points
50 views
0 votes
1 answer

Is there a way to list out in-built variables and functions of Python?

The in-built variables and functions are defined ...READ MORE

answered May 14 in Python by Junaid
37 views
+2 votes
2 answers

In a list of dictionaries, how can I find the minimum calue in a common dictionary field.

There are several options. Here is a ...READ MORE

answered Apr 10, 2018 in Python by charlie_brown
• 7,720 points
69 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 283 views
0 votes
1 answer

Is arr.__len__() the preferred way to get the length of an array in Python?

my_list = [1,2,3,4,5,6,7] len(my_list) # 7 The same works for ...READ MORE

answered Oct 8, 2018 in Python by SDeb
• 13,160 points
66 views
0 votes
1 answer

Create a nested directory in Python

Try os.path.exists, and consider os.makedirs for the ...READ MORE

answered Oct 16, 2018 in Python by SDeb
• 13,160 points
144 views