LMc
LMc

Reputation: 18712

Create dictionary of statistics for several lists in Python?

I would like to create some basic statistics for several lists of data and store them in a dictionary:

>>> from statistics import mean,median
>>> a,b,c=[1,2,3],[4,5,6],[7,8,9]

The following list comprehension works and outputs stats for "a":

>>> [eval("{}({})".format(op,a)) for op in ['mean','median','min','max']]
[2, 2, 1, 3]

Assigning the list's variable name (a) to another object (dta) and evaluating "dta" in a list comprehension also works:

>>> dta="a"
>>> [eval("{}({})".format(op,eval("dta"))) for op in ['mean','median','min','max']]
[2, 2, 1, 3]

But when I try to tie this all together in a dictionary comprehension, it does not work:

>>> {k:[eval("{}({})".format(op,eval("k"))) for op in ['mean','median','min','max']] for k in ['a','b','c']}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <dictcomp>
File "<stdin>", line 1, in <listcomp>
File "<string>", line 1, in <module>
NameError: name 'k' is not defined

My guess is that the eval is processed before the comprehension, which is why 'k' is not yet defined? Any suggestions for how to get this work or a different routine that would accomplish the same output?

Upvotes: 0

Views: 121

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78564

Do not quote the k in the inner eval:

{k:[eval("{}({})".format(op,eval(k))) for op in ['mean','median','min','max']] for k in ['a','b','c']}
                                 ^

Or drop eval altogether:

[[mean(k), median(k), min(k), max(k)] for k in [a, b, c]]

You can do a simple workaround with the keys to change this to a dictionary comprehension.

Upvotes: 1

phormalitize
phormalitize

Reputation: 91

Try removing the quotation marks around k in your call to eval in the format function.

I ran the following commands:

> from statistics import mean,median
> a,b,c=[1,2,3],[4,5,6],[7,8,9]
> {k:[eval("{}({})".format(op,eval(k))) for op in ['mean','median','min','max']] for k in ['a','b','c']}

and got the following output:

{'a': [2.0, 2, 1, 3], 'c': [8.0, 8, 7, 9], 'b': [5.0, 5, 4, 6]}

Upvotes: 0

Related Questions