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

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

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

Exercises for Python

Exercises for Python

Let’s do some exercises with the for loop in Python, in order to consolidate what we have studied so far.

For this purpose, let’s go back to an exercise in which we used the while, so as to be able to compare the two methods. The exercise can be viewed at this link: example while loop in Python.

Exercises for Python – Exercise 1

Input data 10 integers, count how many even and how many odd numbers have been entered.

First, I initialize the count_o and count_e variables to zero.

Then we simply use a for loop with the range (10).

As you can see, it is not necessary to initialize i to 0 as we did in the while, since the index i still starts from zero, unless otherwise specified in the range() function.

Within the cycle I enter the values ​​and for each value entered I check if even or odd. I use the two variables previously initialized to zero to do this count.

Finally, with the for loop, I display the values ​​of the two variables.

So here is the complete code of our simple program, which uses the for loop in Python:


count_o = count_e = 0

for i in range(10):
     n = int(input('Insert a number: '))
     if n % 2 == 0:
        count_e += 1
     else: 
        count_o += 1

print('The even numbers entered are: ', count_e, '\nThe odd numbers entered are: ', count_o)

Try the code in the online compiler at the following link: Python compiler online

Exercises for Python – Exercise 2

Also this time we take up an exercise done with the while and we will carry it out with the for loop in Python, in order to be able to compare these two constructs again.

Take 15 integers as input and calculate the average.

First I initialize n to 15.

Simply because in this way, if for example I have to enter a number other than 15, just change the constant and no other data needs to be changed in the code.

Then with a for loop I ask for the numbers and store them in an average variable which I initialize to 0.

So I can solve the algorithm in this way using the for loop in Python:


average = 0

n = 15

for i in range(n):
     a = int(input('Insert a number: '))
     average += a;

average /= n
print('average is: ', average)

N.B. I use the mean variable for the sum and also for the mean, but I could also use two distinct variables if there was a need to display the sum as well.

In the next lesson I will propose some more exercises on the for loop in Python.

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

List Python

List Python

List in Python is an ordered series of values ​​identified by an index.

So a list is a composite data that aggregates values ​​of any type, enclosed in a pair of square brackets and separated by a comma.

Values ​​that are part of a list are called elements and can be numbers or strings.

Examples of list in Python

So let’s take examples of lists in Python.

Let’s create a list named votes that contains the numeric values ​​from 6 to 9 and also a string, for example Excellent.

votes = [6,7,8,9, ‘Excellent’]

So, as mentioned before, the values ​​can be of different types.

Let’s take another example of a list that contains values ​​of the same type.

So let’s create a list called seasons, in which we memorize the seasons of the year.

Then we print the list with the print function.

seasons = [‘Spring’, ‘Summer’, ‘Autumn’, ‘Winter’]

print (seasons)

It will print: [‘Spring’, ‘Summer’, ‘Autumn’, ‘Winter’]

Index of the list in Python

As we have already said, each element of the list is assigned an index that starts from the left and starts from 0. So, to print for example the first element we write:

print (seasons [0])

While to print the last element we write:

print (seasons [3])

As we have seen with strings, also with lists we can extract a set of values, that is a sublist:

print (seasons [: 2])

This output will only display the first two items in the list.

Editing list elements in Python

The elements of the list can also be modified by reassigning them a new value.

For example, we assign the value ‘Summer’ to the first element, while the value ‘Spring’ is assigned to the second.

seasons [0] = ‘Summer’

seasons [1] = ‘Spring’

In this simple example I have changed the first and second seasons.

Conclusion

In this lesson we introduced the concept of list in Python, in the next we will talk about the length of a list.

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