Shubham
Shubham

Reputation: 85

Counting particular item in defaultdict list

So here is the structure of my defaultdict

#x = {lead_id:[[month,pid,year]]
x={'123':[[1,9,2015],[2,9,2015]],'345':[[2,10,2015],[2,13,2014]],'159':[1,3,2015].....}

I have more than 1000 lead_id's in this dictionary. Each one has random number of lists.In the other words, that same lead_id has duplicates but with different month or pid or year. Now i want to count all the lead_id's in January 2015.I want to count it as two if its two times or more than that according to its occurrence . Can anyone please help me to figure out how i can make an automated code so that it will check the length as well as the number of times that month with same year occurred.

For example:
x={'123':[[1,3,2015],[2,5,2014],[1,5,2015]],'987':[[3,55,2014]],'456':[[1,37,2015]]}
count of jan 2015 = 3

Upvotes: 1

Views: 230

Answers (3)

gsb-eng
gsb-eng

Reputation: 1209

You can use this also...

sum(1 for i in x for j in x[i] if j[0] == 1 and j[2] == 2015)

Upvotes: 5

O.rka
O.rka

Reputation: 30747

You can do conditionals on the index values. date[0] is 1 for Jan. date[2] is 2015

#!/usr/bin/python

x={'123':[[1,3,2015],[2,5,2014],[1,5,2015]],'987':[[3,55,2014]],'456':[[1,37,2015]]}

#Set query dates
query_month = 1 #jan
query_year = 2015 #year

#Set a counter
jan_counts = 0
for list_of_dates in x.values():
    for date in list_of_dates:
        if (date[0] == query_month) and (date[2] == query_year): 
            jan_counts += 1
print jan_counts
#3

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213371

This should give your result:

>>> day = 1
>>> year = 2015
>>> x = {'123':[[1,3,2015],[2,5,2014],[1,5,2015]],'987':[[3,55,2014]],'456':[[1,37,2015]]}
>>> sum([1 for k, v in x.iteritems() for i in v if i[0] == day and i[2] == year])
3

Upvotes: 1

Related Questions