Python - How to count number of occurrences

645 views Asked by At

I'm using the jira-python library to query data from jira. I'm getting back the data I need from jira but processing the data has been giving me issues.

I'm looking to count the occurrences of all components returned from my query. For example, my query will return the results:

Component A
Component B
Component A
Component C

The results I'm looking for is something like:

Component A, 2
Component B, 1
Component C, 1

Here is a snippet of my current code:

search = 'jira query'
issues = jira.search_issues(search, maxResults=100)
for issue in issues:
    [c.name for c in issue.fields.components]

From here I have tried to count and sum c.name

sum(1 for c.name in issue.fields.components)

However this wouldn't produce the correct results as I would get results like counting the number of character occurrences for each result.

Any insight/help would be greatly appreciated

3

There are 3 answers

0
Kevin On

Pass the list/generator expression of names to a collections.Counter object.

0
Hackaholic On
import collections
>>> my_result = '''Component A
... Component B
... Component A
... Component C'''
>>> my_result = my_result.split('\n')   # if they are saperated by newline
>>> my_result
['Component A', 'Component B', 'Component A', 'Component C']
>>> my_result_count = collections.Counter(my_result)
>>> my_result_count
Counter({'Component A': 2, 'Component B': 1, 'Component C': 1})
>>> for x in sorted(my_result_count.keys()):
...     print x + ", " + str(my_result_count[x])
... 
Component A, 2
Component B, 1
Component C, 1

collections.Counter will return dictionary vihh word and its occurance

0
ThePavolC On

Go through issues and components and count them.

# dictionary where we will hold results of counting of componets
count_result = {}

# we search for issues we are interested in
issues = jira.search_issues("project = PROJECT_KEY", maxResults=100)
for issue in issues:
    # in case there is more components we iterate through them all
    # and count them in count_result dictionary
    for component in [c.name for c in issue.fields.components]:
        if count_result.get(component):
            # if component already exists in count_result dictionary
            count_result[component] += 1
        else:
            # if component doesn't exists in count_result dictionary
            count_result[component] = 1

# print out of result
for name,value in count_result.items():
    print "%s, %d" % (name, value)