Python, counting repeated name

Issue

def name_counts(alist):
    split = []
    for listitem in alist:
        split.extend(listitem.split())
    dicti = {}
    for word in split:
        if word in dicti:
            dicti[word] +=1
        else:
            dicti[word] = 0
    print(split)
    return dicti


name_list = ["David Joyner", "David Zuber", "Brenton Joyner",
             "Brenton Zuber", "Nicol Barthel", "Shelba Barthel",
             "Shelba Crowley", "Shelba Fernald", "Shelba Odle",
             "Shelba Fry", "Maren Fry"]
print(name_counts(name_list))

This function should return dictionary dicti where key is name / lastname from the list listand value of the key is the number of times the name or lastname repeats in that list.

def name_counts(alist):
        split = []
        for listitem in alist:
            split.extend(listitem.split())

This part of code converts the alist which has the value of name_list to a list where each name and lastname are separate values in the list. This list with names and last name separated is called split. When i check the code at this point, It works, it prints the split and i t has all the names and lastnames separated.

The problem is that the following code doesn’t count the repeating names or lastnames correctly, function still runs but the amount of times the names and last names appear in the list split is incorrect.

The problem is in this part of code:

dicti = {}
    for word in split:
        if word in dicti:
            dicti[word] +=1
        else:
            dicti[word] = 0

Help

Solution

The counts are off by 1, because the first time you see the name, you initialize that name’s count to 0. If you’re going to keep the current flow-control structure, you should initialize the count to 1 at that point instead of 0.

But here’s a more compact version that avoids luring you into that mistake:

def name_counts(alist):
    split = [name for listitem in alist for name in listitem.split()]
    return {name : split.count(name) for name in set(split)}

Note the use of set(split) to give you the set of unique names, over which you then iterate to do the counting.

And actually, there’s also an off-the-peg counting dictionary, called Counter, in Python’s standard library:

import collections
def name_counts(alist):
    return collections.Counter(name for listitem in alist for name in listitem.split())

Answered By – jez

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published