MrB
MrB

Reputation: 818

Adding values to dictionary, int is not iterable

I'm trying to either add a new value to a dictionary or increment the value (depending on whether the key is found or not) and I'm running in to an error message saying:

Traceback (most recent call last): File "C:/Users/james/Desktop/names.py", line 30, in scores(boys) File "C:/Users/james/Desktop/names.py", line 14, in scores totals.update(map(score,1)) TypeError: 'int' object is not iterable

The line throwing the problem is:

totals.update(map(score,1))

and the full code is:

import csv
def scores(names):
    totals = {}
    values = {"a": 1, "b": 3, "c": 3, "d": 2, "e": 1, "f": 4, "g": 2, "h": 4, "i":1, "j": 8, "k": 5, "l": 1, "m": 3, "n": 1, "o": 1, "p": 3, "q": 10, "r": 1, "s": 1, "t": 1, "u": 1, "v":4, "w": 4, "x": 8, "y": 4, "z": 10}
    score = 0
    for name in names:
        for letter in name:
            letter = letter.lower()
            if (letter in values):
                score = score + int(values.get(letter))
        if (score in totals):
            totals.update(map(score,score.get(score)+1))
            #presumably this would throw an error
        else:
            totals.update(map(score,1))
            #this is the line throwing the error
        score = 0
    print (totals)    

boys = set()
girls = set()
with open ("names.txt") as file:
    reader = csv.reader(file, delimiter=' ', quotechar='|')
    for row in reader:
        row = row[0].split(",")
        if (row[0]=="B"):
            boys.add(row[1])
        else:
            girls.add(row[1])
print (len(boys))
print (len(girls))
scores(boys)
scores(girls)

For context, I have a massive csv of Scottish children's names 1974-2016 stored as names.txt and I'm trying to get the frequency of the different Scrabble scores for them. I've looked at this question and the answers linked from it but, as best I can tell, I'm not actually trying to iterate over score

Upvotes: 1

Views: 227

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140186

this block cannot work because map takes an iterable as second argument (you don't need map at all here, map applies a function to all elements of an iterable)

    if (score in totals):
        totals.update(map(score,score.get(score)+1))
    else:
        totals.update(map(score,1))

Behind your totally bogus code (had to be said :)), you want to count how many times a given score is reached, so you need:

import collections
totals = collections.Counter()

then simply:

totals[score] += 1

Upvotes: 1

Related Questions