Medium, Minimum and Maximum in a python dictionary

Asked

Viewed 1,751 times

0

I have a dictionary like that:

{walt: 0.942342, disney: 0.324234, robert: 0.562354, help: 0.546912, ...}

And I do it to find the average and the maximum:

media = statistics.mean(dicContadores.values())
counter = collections.Counter(dicContadores.keys())
maximo = counter.most_common(1)
minimo = min(dicContadores.items(), key=lambda x: x[1])

print("   Média: ", media)
print("   Máximo: ", maximo)
print("   Minimo: ", minimo)

The way this one got this output:

 Média: 0.0714285
 Máximo: [('walt', 1)]
 Minimo: ('disney', 0.324234)

But I have one problem: How do I make the associated value not to be rounded at most?

  • You edited and put [solved], it would not be interesting to share the solution?

  • The solution has already been put, when I put [solved]

  • 3

    @Walt057 Sopt uses the structure of questions and answers, separating very well what is each thing. The question is to ask, the answer to answer. If you have the solution to your problem, always post as reply. Read about Answer your own question. Also, it is unnecessary to add "[solved]" in the title. This is a limitation that other people’s forums have, but Sopt does not. Read about this How and why to accept an answer?

2 answers

4


Dictionaries define an injecting relationship between keys and values, a map, so it makes no sense to be orderly (or better, classifiable).

In order to rank the maximum and minimum, you will need to create another structure that is classifiable. You already asked that question when you used dicContadores.items(), that returns an iterable containing tuples of two values being the key and the value, respectively.

But you can also do this implicitly through the parameter only key of max() and min(). When used, you implicitly create in memory another structure that will be used for the classification of values.

maximo = max(dicContadores, key=dicContadores.get)
minimo = min(dicContadores, key=dicContadores.get)

Thus, maximo and minimo will be the keys where maximum and minimum values occur within the dictionary.

0

d={"a": 3, "b": 2}
minimo = min(d, key=d.get)
print(minimo)
maximo = max(d, key=d.get)
print(maximo) código aqui

Now that’s right, I’ve really made a mistake.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.