Sort dictionary by value and use rule if value is first python

Asked

Viewed 959 times

0

I want to make a dictionary in python in which you will get diseases and scores ex: dic['alzhelmer']=3 dic['flu']=5

The program should put in order the diseases that scored the most for those who scored the least (decreasing) in the dictionary ex:

dic['flu']=5 dic['alzhelmer']=3

And finally if for example flu is the one that scores the most, give a command.

ex: if dic['gripe'] == maiorpontuador:

    "url= gripe.com"

Thank you very much!!!

  • Related: https://answall.com/q/233096/5878

1 answer

1

Python dictionaries are not "orderly". There are several other objects that can be sorted in python, so I suggest you use one of them and then transfer them to an Ordereddict dictionary (which, unlike a common dictionary, keeps the order in which it was created whenever you access it), for example:

from collections import OrderedDict

# Criando pontuações em lista de tuplas (poderia ser lista de listas)
data = [('Asma', 6), ('Cachumba', 5), ('Difteria', 4),('Rubeola', 9)]

# Criando o dicionario
od = OrderedDict([par for index, par in sorted((tpl[1], tpl) for tpl in data)])

print (od)
OrderedDict([('Difteria', 4), ('Cachumba', 5), ('Asma', 6), ('Rubeola', 9)])

print(od['Cachumba'])
5

Edited
If you want it in reverse order:

# Criando pontuações em lista de tuplas (poderia ser lista de listas)
data = [('Asma', 6), ('Cachumba', 5), ('Difteria', 4),('Rubeola', 9)]

# Criando a indexação na ordem reversa
dr = sorted([(tpl[1], tpl) for tpl in data], reverse=True)

# Criando o dicionário
od = OrderedDict([tpl[1] for tpl in dr])

print (od)
OrderedDict([('Rubeola', 9), ('Asma', 6), ('Cachumba', 5), ('Difteria', 4)])

Obs.:
If your list is already sorted, then just create the dictionary (Ordereddict) normally. As for the question of the "command" at the end of the question, I could not understand, the purpose of dictionaries is only to map keys/values.

Browser other questions tagged

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