Occurence of name in dictionary

I am running into a problem and no clue what to do, as I am new to programming. The situation is as follows, we extracted data from a .txt file with names, children etc. and extracted it into a dictionary. The dictionary is accessed with the name as the key, e.g:

# access a single person in allPersons via the name as key
p1 = allPersons['jan']
print("Name:", p1.name)
print("Sex:", p1.sex)
for p in p1.children:

with the output being:

Name: jan

Sex: female


So far so good, but now I am expected to write a function called count which stores the name so for example ‘stefan’ as the key and the number of occurences as the value for the key, while ignoring numeric suffixes to the name such as ‘stefan02’ or ‘stefan10’ and to be honest I am really lost on this.

def count(persons):
    name_counts = {}
    raise NotImplementedError()
    return name_counts
assert count(allPersons)['stefan'] == 20

I tried messing around with code I found online and imports such as regex but honestly I got even more confused than before and I was hoping I could get some pointers in the right direction. While I’m kinda embarassed to show my code since it is probably wrong, I’m still going to put the miniscule amount I do have on here, to show I have indeed been thinking about the problem myself.

def count(persons):
    name_counts = {}
    for j in persons:
        if j in name_counts:
    return name_counts

The error I get is ‘nora11’ which is the first name to be fed from the .txt into the dictionary as context.

Thank you in advance!

>Solution :

occu = {}
for p in persons:
    for i,k in enumerate(p):
        if k.isdigit():
            p = p[:i]
    if p in occu:
        occu[p] += 1
        occu[p] = 1

Hope this helps

edit: this doesn’t work if the digits are not at the end of the name, eg

tom    --> tom
tom123 --> tom
to123m --> to
123tom --> 

Leave a Reply