getting an average of values from dictionaries with keys with a list of values
<p>For my final python assignment at my university I need to create functions within Jupyter Notebook to conduct a small research. I need to create dictionaries and lists from .csv files and build functions for the dictionaries that I get from my read_csv() function. For this assignment I am allowed to ask and google because the functions I have to make are fairly common problems people walk into.</p>

<p>The way these dictionaries look like after my read_csv() returns them is as follows:</p>

<pre><code>data_dict = { "abc" : [1, 2, 3, 4],
              "def" : [4, 5, 6, 7],
              "ghi" : [8, 9, 10, 11]
            }
</code></pre>

<p>So basically a dictionary with a large amount of keys with each a list of values. What I need to do is sum up all the numbers of the first index of each list and get the average from the sum, then the second index, third index and so on, returning a list of all averages. With the result being something like:</p>

<pre><code>averages = [4.333, 5.333, 6.333, 7.333]
</code></pre>

<p>How would one go about this without importing anything? In the past weeks we haven't really talked about working with dictionaries and I've tried looking for solutions on the internet but couldn't find any dealing with summing up integers or floats at specific indexes from different lists.</p>

<p>First collect the values, transpose them and then its easy:</p>

<pre><code># values of the dict
values = data_dict.values()

# transposed average
averages = [sum(x)/float(len(x)) for x in zip(*values)]
print (averages)
</code></pre>

<p>returns:</p>

<pre><code>[4.333333333333333, 5.333333333333333, 6.333333333333333, 7.333333333333333]
</code></pre>

<p>A shorter <em>'less-explanatory'</em> one-liner would be:</p>

<pre><code>averages = [sum(x)/float(len(x)) for x in zip(*data_dict.values())]
</code></pre>

python list python-2.7 dictionary jupyter-notebook