-1

I am trying to add values to a list inside a dictionary. I have had a look at this and tried append, but I get an error.

Code:

def name_counts(x):
    firsts = {}
    for full in x:
        part = full.split()
        fn = part[0]
        if fn in firsts:
            firsts[fn].append(full)
        else:
            firsts[fn] = []
            firsts[fn] = full
    return(firsts)


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))

Error:

AttributeError: 'str' object has no attribute 'append'

Desired output:

{'Shelba': ['Shelba Barthel', 'Shelba Crowley', 'Shelba Fernald', 'Shelba Odle', 'Shelba Fry'],'David': ['David Joyner', 'David Zuber'], 'Brenton': ['Brenton Joyner', 'Brenton Zuber'], 'Maren': ['Maren Fry'], 'Nicol': ['Nicol Barthel']}
4
  • firsts[fn] = full ...? Commented Jun 25, 2019 at 12:13
  • 2
    Try firsts[fn] =full as firsts is a dictionary. Commented Jun 25, 2019 at 12:13
  • 1
    @ArkistarvhKltzuonstev what do you mean "try"? That line is the problem. Commented Jun 25, 2019 at 12:14
  • 1
    seems like a good use case for defaultdict Commented Jun 25, 2019 at 12:35

2 Answers 2

2

When you create the list you are immediately replacing it with a string. Try:

if fn in firsts:
    firsts[fn].append(full)
else:
    firsts[fn] = [full]

instead of

if fn in firsts:
    firsts[fn].append(full)
else:
    firsts[fn] = []
    firsts[fn] = full
Sign up to request clarification or add additional context in comments.

Comments

2
def name_counts(x):
firsts = {}
for full in x:
    part = full.split()
    fn = part[0]
    if fn not in firsts:
        firsts[fn] = []

    firsts[fn].append(full)
return(firsts)


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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.