6

I have a dictionary in the form:

{"a": (1, 0.1), "b": (2, 0.2), ...}

Each tuple corresponds to (score, standard deviation). How can I take the average of just the first integer in each tuple? I've tried this:

for word in d:
    (score, std) = d[word]
    d[word]=float(score),float(std)
    if word in string:
        number = len(string)
        v = sum(score)
        return (v) / number

Get this error:

    v = sum(score)
TypeError: 'int' object is not iterable
Georgy
  • 12,464
  • 7
  • 65
  • 73
Billy Mann
  • 87
  • 1
  • 1
  • 4

1 Answers1

8

It's easy to do using list comprehensions. First, you can get all the dictionary values from d.values(). To make a list of just the first item in each value you make a list like [v[0] for v in d.values()]. Then, just take the sum of those elements, and divide by the number of items in the dictionary:

sum([v[0] for v in d.values()]) / float(len(d))

As Pedro rightly points out, this actually creates the list, and then does the sum. If you have a huge dictionary, this might take up a bunch of memory and be inefficient, so you would want a generator expression instead of a list comprehension. In this case, that just means getting rid of one pair of brackets:

sum(v[0] for v in d.values()) / float(len(d))

The two methods are compared in another question.

Community
  • 1
  • 1
Mike
  • 19,114
  • 12
  • 59
  • 91
  • 3
    You don't actually need the list comprehension, `sum` will take any iterable, so the generator expression in `sum(v[0] for v in d.values())` will work without creating the intermediate list. – Pedro Romano Oct 20 '12 at 21:09
  • 1
    Excellent point. I just think building up the expression like this is a bit clearer. – Mike Oct 20 '12 at 21:11