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, 2019 in Python by ana1504.k
• 7,910 points
1,392 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, 2019 by SDeb
• 13,300 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
• 58,020 points
2,338 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 23, 2018 in Python by aryya
• 7,460 points
2,910 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, 2019 in Python by Junaid
2,216 views
0 votes
0 answers

number of occurrence counting in a string

Write a function called number_of_occurrences that takes ...READ MORE

May 16, 2020 in Python by Anny
• 120 points
2,381 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,422 views
0 votes
1 answer
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,300 points
943 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,300 points
1,600 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP