Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average of the first items of tuples in a dict

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
like image 696
Billy Mann Avatar asked Oct 20 '12 20:10

Billy Mann


People also ask

What is Dictionary of tuples in Python?

Dictionary of tuples means tuple is a value in a dictionary or tuple is key in the dictionary. {'key1': (1, 2, 3), 'key2': (3, 2, 1),.............} or { (1, 2, 3):value, (3, 2, 1):value,.............}

How to sort the Dictionary of tuples based on keys and values?

{'key1': (1, 2, 3), 'key2': (3, 2, 1),.............} or { (1, 2, 3):value, (3, 2, 1):value,.............} Using this method we can sort the dictionary of tuples based on keys, values, and items, we can use for loop to sort all elements in a dictionary of tuples.

What is the Order of tuples?

Tuple items are ordered, unchangeable, and allow duplicate values. Tuple items are indexed, the first item has index [0], the second item has index [1] etc. When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.

What is the difference between dictionary and set and tuples?

Tuple is a collection which is ordered and unchangeable. Allows duplicate members. Set is a collection which is unordered and unindexed. No duplicate members. Dictionary is a collection which is ordered* and changeable. No duplicate members.


1 Answers

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.

like image 92
Mike Avatar answered Oct 10 '22 11:10

Mike