Sort dictionary Python

Sort dictionary Python

You can sort a dictionary in Python by key or by value. Let’s do some practical examples of sorting in Python according to our needs.

All the proposed examples can be tested in the online compiler that you will find at the following link: Python compiler online.

First example – Sort a dictionary in Python by key

In this first example we first create a dictionary in Python. We then said to sort by key, so we have to decide whether to follow an ascending or descending order, finally we have to call the function on the dictionary.

So let’s implement a first solution. To sort in ascending order we can use the sorted function on our dictionary, like this:


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

for key in sorted(student):
    print(key, student[key])

What if we want a descending order? Simply use the reverse parameter of the sorted function, setting it to False.

Here is an example of a descending dictionary in Python:


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

for key in sorted(student, reverse = True):
    print(key, student[key])

Second example – Sort a dictionary in Python by key

Let us now seek a second solution to the proposed problem.

First, for example, we could think of using the keys() method on the dictionary, but what happens?

So let’s try it with an example:


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

sorted_key = sorted(student.keys())

for element in sorted_key:
  print(element)

In this case you will have the following output:

age
hobby
mail
name
passion

That is, we will have only the keys ordered in ascending order.

So even if I use the dict () method I won’t be able to sort a dictionary in Python this way.

What if we try to use the values​​() method instead?


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

sorted_values = sorted(student.values())

for element in sorted_values:
  print(element)

The result will be the following:

29
Cristina
coding
codingcreatico@gmail.com
swim

So if I want to sort a dictionary in Python by key what should I do? What other solution can I think of?

We can, for example, use the items() method, which we studied in this lesson: items Python.

We also remind you that this method is used to return the list with all the dictionary keys with their respective values.

After that, we can again convert the pairs of tuples back into a dictionary using the dict () method.

Here is a possible solution to our algorithm:


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

sorted_student = sorted(student.items())
sorted_student_dict = dict(sorted(student.items()))

print(sorted_student_dict)

for element in sorted_student_dict:
  print(element, ': ', sorted_student_dict[element])

So we got all the key tuple pairs, values ​​sorted in ascending order. Then, let’s convert it to a dictionary with the dict () method. So we can sort the dictionary in Python by key.

We use a function to then be able to use it to create the order on multiple dictionaries:


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

def sort_dict(d):
  return dict(sorted(student.items()))

print(sort_dict(student))

Sort a dictionary in Python by key in descending order

This time we use the reverse parameter of sorted to create a descending sort on the dictionaries. In fact, setting it to True the sorting will be descending. By default its value is False.


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

def sort_dict(d):
  return dict(sorted(student.items(), reverse = True))

print(sort_dict(student))

For the sake of completeness we could also pass this parameter to the function, like this:


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

def sort_dict(d, rev):
  return dict(sorted(student.items(), reverse = rev))

print(sort_dict(student, True))

Conclusion

In this lesson we have covered some interesting examples of how to sort a dictionary in Python by key, in ascending and descending order.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

Python

Bubble sort

Matplotlib Plot

Ordinare un dizionario in Python

Ordinare un dizionario in Python

Si può ordinare un dizionario in Python per chiave o per valore. Facciamo alcuni esempi pratici di ordinamento in Python in base alle nostre esigenze.

Tutti gli esempi proposti possono essere provati nel compiler online che troverete al seguente link: Python compiler online.

Primo esempio – Ordinare un dizionario in Python per chiave

In questo primo esempio dapprima creiamo un dizionario in Python. Abbiamo poi detto di ordinare per chiave, quindi dobbiamo decidere se seguire un ordine crescente o decrescente, infine dobbiamo richiamare la funzione sul dizionario.

Implementiamo, dunque, una prima soluzione. Per ordinare in senso crescente possiamo utilizzare la funzione sorted sul nostro dizionario, in questo modo:


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

for key in sorted(student):
    print(key, student[key])

E se vogliamo un ordinamento decrescente? Basterà semplicemente utilizzare il parametro reverse della funzione sorted, impostandolo a False.

Ecco un esempio di dizionario ordinato in senso decrescente in Python:


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

for key in sorted(student, reverse = True):
    print(key, student[key])

Secondo esempio – Ordinare un dizionario in Python per chiave

Cerchiamo adesso una seconda soluzione al problema proposto.

Innanzitutto potremmo ad esempio pensare di utilizzare il metodo keys() sul dizionario, ma cosa succede?

Proviamolo, dunque, con un esempio:


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

sorted_key = sorted(student.keys())

for element in sorted_key:
  print(element)

In questo caso si avrà il seguente output:

age
hobby
mail
name
passion

Ovvero avremo le sole chiavi ordinate in senso crescente.

Quindi, anche se uso il metodo dict() non riuscirò in questo modo ad ordinare un dizionario in Python.

E se invece proviamo ad utilizzare il metodo values()?


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

sorted_values = sorted(student.values())

for element in sorted_values:
  print(element)

Il risultato sarà il seguente:

29
Cristina
coding
codingcreatico@gmail.com
swim

Quindi se voglio ordinare un dizionario in Python per chiave cosa devo fare? Quale altra soluzione posso pensare?

Possiamo, ad esempio, utilizzare il metodo items(), che abbiamo studiato in questa lezione: items Python.

Ricordiamo inoltre che questo metodo è utilizzato per restituire l’elenco con tutte le chiavi del dizionario con i suoi rispettivi valori.

Dopo, possiamo nuovamente riconvertire le coppie di tuple in un dizionario utilizzando il metodo dict().

Ecco una possibile soluzione al nostro algoritmo:


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

sorted_student = sorted(student.items())
sorted_student_dict = dict(sorted(student.items()))

print(sorted_student_dict)

for element in sorted_student_dict:
  print(element, ': ', sorted_student_dict[element])

Così abbiamo ottenuto tutte le coppie di tuple chiave, valori ordinate in senso crescente. Poi, convertiamolo in dizionario con il metodo dict(). Così riusciamo ad ordinare il dizionario in Python per chiave.

Utilizziamo una funzione per poterla poi utilizzare per creare l’ordinamento su più dizionari:


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

def sort_dict(d):
  return dict(sorted(student.items()))

print(sort_dict(student))

Ordinare un dizionario in Python per chiave in senso decrescente

Questa volta utilizziamo il parametro reverse di sorted per creare un ordinamento decrescente sui dizionari. Infatti impostandolo a True l’ordinamento sarà decrescente. Di default il suo valore è False.


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

def sort_dict(d):
  return dict(sorted(student.items(), reverse = True))

print(sort_dict(student))

Per completezza potremmo passare questo parametro anche alla funzione, in questo modo:


student = {
    "name": 'Cristina',
    "age": '29',
    "hobby": 'swim',
    "mail": 'codingcreatico@gmail.com',
    "passion": 'coding'
}

def sort_dict(d, rev):
  return dict(sorted(student.items(), reverse = rev))

print(sort_dict(student, True))

Conclusione

In questa lezione abbiamo affrontato alcuni interessanti esempi su come ordinare un dizionario in Python per chiave, in ordine crescente e decrescente.

Alcuni link utili

Indice tutorial sul linguaggio Python

1 – Introduzione al linguaggio Python

2 – Le variabili

3 – Operatori aritmetici e di assegnazione

4 – Stringhe

5 – Casting

6 – Input e print

7 – Primi esercizi in Python

8 – Errori in Python

9 – Script Python

10 – Scambio di variabili

11 – Modulo math

Python continue

Python continue

Python continue statement allows us to stop the current iteration to start over from the first statement of the loop (for or while) in which it was entered.

Python continue – first example

So let’s take a simple example to better understand how it works.

We enter numbers, if the number is negative we use the continue statement to make it skip all the other lines of code and start again from the beginning.

Here is the simple program:


i = 0
while i <3:
   n = int(input('Insert a number: '))
   if n < 0:
       continue
   i += 1

In this case, therefore, if we insert a negative number, the counter is not incremented and the cycle continues to insert numbers until all 3 are positive.

Try the code in the online compiler that you will find at the following link: Python compiler online.

Python continue - second example

Let's take a second example of using the continue statement in Python.

We print numbers from 1 to 10, skipping the number 5.

Here, then, is an example with the for loop:


for i in range(1,11):
  if i == 5:
    continue
  print(i)

The output produced is this:

1
2
3
4
6
7
8
9
10

As we can see, the number 5 was not printed.

Python continue - third example

Let's take another example to better understand how this instruction works.

Print the numbers 1 to 10 by skipping multiples of 3.

Here is the sample code:


for i in range(1,11):
  if i % 3 == 0:
    continue
  print(i)

The output produced is as follows:

1
2
4
5
7
8
10
As we can see, the numbers 3, 6 and 9 were not printed.

Conclusion

In this short lesson we have explained how the continue statement works in Python through simple examples.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

How to use the math module

Bubble sort

Matplotlib Plot

Continue Python

Continue Python

L’istruzione continue in Python consente di stoppare l’iterazione corrente per ripartire nuovamente dalla prima istruzione del ciclo (for o while) dove è inserito.

Primo esempio d’uso dell’istruzione continue in Python

Facciamo quindi un semplice esempio per capire meglio il funzionamento.

Inseriamo dei numeri, se il numero è negativo utilizziamo l’istruzione continue per fargli saltare tutte le altre linee di codice e ripartire dall’inizio.

Ecco, di seguito, il semplice programma:

i = 0

while i < 3:
   n = int(input('Inserisci il numero: '))
   if n < 0:
       continue
   i += 1

In questo caso, dunque, se inseriamo un numero negativo il contatore non viene incrementato ed il ciclo continua ad inserire numeri finchè non sono tutti e 3 positivi.

Provate il codice nel compiler online che troverete al seguente link: Python compiler online.

Secondo esempio d’uso dell’istruzione continue in Python

Facciamo un secondo esempio d’uso dell’istruazione continue in Python.

Stampiamo dei numeri da 1 a 10, saltando il numero 5.

Ecco, dunque, un esempio con il ciclo for:

for i in range(1,11):
  if i == 5:
    continue
  print(i)

L’output prodotto è questo:

1
2
3
4
6
7
8
9
10

Il numero 5 non è stato stampato.

Terzo esempio d’uso dell’istruzione continue in Python

Facciamo un altro esempio per capire meglio il funzionamento di questa istruzione.

Stampare i numeri da 1 a 10 saltando i multipli di 3.

Ecco il codice di esempio:

for i in range(1,11):
  if i % 3 == 0:
    continue
  print(i)

L’output prodotto è il seguente:

1
2
4
5
7
8
10

I numeri 3, 6 e 9 non sono stati stampati.

Migliora le tue capacità di programmazione Python seguendo i nostri corsi in diretta!

corsi Python

Conclusione: Massimizzare l’efficienza con l’istruzione continue in Python

In questo articolo, abbiamo esplorato l’uso dell’istruzione continue in Python e come possa essere impiegata per ottimizzare il flusso di esecuzione dei loop. Attraverso una serie di esempi pratici, abbiamo dimostrato la versatilità di questa istruzione nel saltare specifiche iterazioni del ciclo, permettendo così di gestire condizioni particolari senza interrompere completamente l’esecuzione del loop.

Dal saltare l’iterazione corrente in un ciclo “while” quando viene inserito un numero negativo, al filtrare i valori da stampare in un ciclo “for” escludendo il numero 5 o i multipli di 3, l’istruzione “continue” si rivela un utile strumento per ottimizzare il codice e migliorarne la leggibilità.

Sfruttare appieno l’istruzione “continue” ci consente di scrivere codice più conciso ed efficiente, evitando la necessità di aggiungere complesse strutture condizionali all’interno dei loop. Questo non solo migliora la manutenibilità del codice, ma anche la sua velocità di esecuzione.

In conclusione, l’istruzione continue è un prezioso alleato nella scrittura di codice Python pulito ed efficiente.

Alcuni link utili

Corso in diretta su Python

Indice tutorial sul linguaggio Python

1 – Introduzione al linguaggio Python

2 – Le variabili

3 – Operatori aritmetici e di assegnazione

4 – Stringhe

5 – Casting

6 – Input e print

7 – Primi esercizi in Python

8 – Errori in Python

9 – Script Python

10 – Scambio di variabili

11 – Libreria math

12 – Operatori di confronto e booleani

13 – If else

14 – If elif else

15 – If annidati

Break Python

Break Python

Break in loops in Python – In this lesson we will study how to use the break statement in loops. This instruction is useful when we want to terminate the loop following a condition and usually go to the next code.

The break statement in Python, like in many other programming languages, allows you to exit the for or while loop immediately.

Break can be used in all loops, even nested loops. If used in nested loops, only the loop it is placed in will be terminated and other loops will continue as normal.

Break Python – first example with while

Let’s take a practical example immediately, with while loop.

Enter numbers and add them. As soon as you enter a negative number, you exit the while loop.

Here is a possible implementation of the proposed algorithm.


i = sum = 0

while i < 10:
    n = int(input('Insert a number: '))
    if n < 0:
        break
   sum += n
   i += 1

print('Sum is: ', sum)

In this example as soon as we insert a negative number we immediately exit the loop without adding it. In fact, break causes the immediate exit from the while loop.

Try this example in the online compiler, which you can find at this link: Python compiler online.

Break Python – second example with for

Let’s do the same example using the for this time. Also this time we insert the break when a condition occurs.

So here is a possible implementation:


sum = 0
for i in range(10):
    n = int(input('Insert a number: '))
    if n < 0:
        break
   sum += n
print('Sum is: ', sum)

As we can see also this time, when we insert a negative number, we get out of the loop.

Break Python - third example with for nested

In this example we use the break only in the innermost loop. We enter as a condition, when i equals 1 and j equals 3.

So here is a possible example:


'''
Break Python - FOR LOOP Nested
'''
for i in range(1,3):
    for j in range(1,5):
        print(j, end = '')
        if j == 3 and i == 1:
          break
    print()

In this lesson we have made some examples of breaks in Python, in the next lesson we will talk about continues.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

How to use the math module

Bubble sort

Matplotlib Plot