I have a problem when displaying the keys and values of a dictionary by line. What I want is to print the first key and its value on the first line, the second key and its value on the second line, etc.
Then as a second objective, how could you do the same as before but ordering them from highest to lowest according to the value of each key (number of votes in the exercise)??
This is my code, it is an exercise with "political party" and "number of votes":
partido_y_votos = {}
continuar = "s"
while continuar == "s":
partido_politico = input("ingrese partido politico: ")
cantidad_votos = int(input("ingrese cantidad de votos del partido: "))
# agrega el nombre del partido y sus votos al diccionario.
# si el nombre se repite, se suman los votos ingresados
if partido_politico in partido_y_votos:
partido_y_votos[partido_politico] += cantidad_votos
else:
partido_y_votos[partido_politico] = cantidad_votos
continuar = input("desea continuar? s/n")
I lack that, knowing how to do the last part properly using print. Any help is appreciated in advance :)
The simplest thing is that you use
dict.items
together withsorted
:Departure:
Explanation :
dict.items
is a dictionary method that generates a view of it, an iterable with key-value pairs. For our example we can represent it as:sorted(iterable, *, key=None, reverse=False)
: this built-in function returns a list with the items to order an iterable, the argumentkey
allows to define a function that receives each item as an argument and its return is used to order. The above is similar to something like this:operator.itemgetter
does the function ofordenar_por_segundo_item
, only more efficiently, at the compiled C code level.sorted
basically it takes the "list"[('a', 5), ('d', 2), ('c', 1), ('b', 7)]
returned bydict.items()
, iterates over it and for each element (for example('a', 5)
) calls the function associated withkey
and passes it as an argument and uses its return (5
in this case) to sort the list of tuples, obtaining:Once this is done, we just have to use a
for
to go through it. The variableskey
andvalue
take in each iteration the first element of the tuple and the second respectively (unpacked), so we only have to print them.f"{key}: {value}"
is a formatted string literal, it basically replaces the expression inside every pair of{}
with the value that results from evaluating it. This is available as of Python 3.6 , only. If this is not your case you can do for example:print("{}: {}".format(key, value))
.Extra
In Python, dictionaries haven't traditionally maintained insertion order, so they can't be sorted internally (need to use
collections.OrderedDict
for it). As of Python 3.6 (as an implementation detail only) and Python 3.7 (definitely) dictionaries always keep their original insertion order, which extends to their views.If once the dictionary is created you are not going to update it but you are going to regularly iterate over it with the need for it to be sorted, you can sort it when you create it directly avoiding having to call
sorted
each time. Obviously if you update you will have to reorder it.From this moment and as long as you do not modify it, the dictionary will be ordered according to its values, to print it ordered as many times as you want, simply:
FOR CYCLE
I share your code with what you needed, in each line leave a comment explaining what I did, the most important thing is that with a "for" we obtained all the keys and with these we can send to call its value ("party_and_votes[variable_used_in_the_for ]")