Home > Net >  Why is my for loop not adding all values to the dictionary?
Why is my for loop not adding all values to the dictionary?

Time:04-08

def biggest_family(fil):
    with open(fil) as file:
        name = {}
        ans = {}
        text = file.read().split("\n")
        for i in range (0 , len(text)-1):
            first = text[i].split()
            name[first[0]] = first[1]        
        for b in name:
            if name[b] in ans:
                ans[name[b]]  = 1
            else:
                ans[name[b]] = 1
        print(ans)
           

The output should be a dictionary of the last name of the family and amount of times it is present in the list. For some reason it works perfectly for some datasets and is short a number on others. As you can see in the picture below it prints the simpsons and griffins in the correct amount but not the Lannister family above it in the first test.

enter image description here

CodePudding user response:

The problem is that Cersei Smith replaces Cersei Lannister in the name dictionary in your first loop. Dictionary keys can't be repeated, so you can't have two different Cersei entries.

There's no need for the name dictionary, just create the ans dictionary in that loop.

def biggest_family(fil):
    with open(fil) as file:
        text = file.read().split("\n")
    ans = {}
    for full_name in text[:-1]:
        first_name, last_name = full_name.split()
        if last_name in ans:
            ans[last_name]  = 1
        else:
            ans[last_name] = 1   
    print(ans)

CodePudding user response:

Your question seems to indicate that the output should be printed text rather than a dictionary. There are undoubtedly some impossible to understand comprehensions that will do this with less code but let's take a step-wise approach:

def biggest_family(fil):
    with open(fil) as family:
        d = dict() # empty dictionary
        hi_count = 0 # keep track of the hi number of family members
        for line in map(str.strip, family): # iterate of the file line by line
            forename, surname = line.split() # get the surname and forename
            d.setdefault(surname, []).append(forename) # append to a list value against a surname key in the dictionary
            if (l_ := len(d[surname])) > hi_count: # check the hi count
                hi_count = l_
        output = [] # empty list
        for k, v in d.items(): # iterate over the dictionary looking for families equal to the hi count
            if len(v) == hi_count: # we're interested in this one
                output.append(f'{k} family: {" ".join(sorted(v))}')
        for line in sorted(output): # looks like the output needs to be sorted
            print(line)

biggest_family('family.txt')

I've created a file called family.txt with the content shown in your question. The output of this will be:

Lannister family: Cersei Jaime Tyrion
Stark family: Arya Catelyn Ned
  • Related