List and Dictionary Comprehension

These are efficient ways to initializing a List and a Dictionary. They are really good for practical use and help a lot in the long run. This unit is a key to writing better code in Python. We will be mixing a lot of concepts we have learnt so far, and do some really cool stuff!

List Comprehension

In the previous chapters, we have discussed how to create a List. This might help us recall that:

list = []
for i in range(1,11):
    list.append(i)
print(list)

This outputs:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Sometimes writing 3-4 lines of code for a simple task as above can be inefficient, especially for the long programs serving a much important purpose. List comprehension helps us do the above in just one expression! The basic form is:

list = [<expression> for <variable> in <iterable>]

To demonstrate, the code we just wrote becomes:

list = [i for i in range(1,11)]

It outputs:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

This is not it, there is another feature we have with List comprehension. What if there are some conditions we wish to apply while doing List comprehension? For example, picking only even numbers from 1 to 10. This is the basic form:

list = [<expression> for <variable> in <iterable> if <condition>]

The new code would be:

list = [i for i in range(0,11) if i%2 == 0]

The output becomes:

[0, 2, 4, 6, 8, 10]

DID YOU NOTICE? We can also use range(0,11,2) for the code above! This is just to observe how efficient and flexible Python is.

Dictionary Comprehension

Just like List comprehension, Dictionary comprehension is also possible. This is also quite easy to understand.

For this we will need to make a csv file using Google Sheets, Microsoft Excel or any other spreadsheet software. Let's consider the example of the employees in a firm. So our excel will have the name and their salary as the data in two different columns:

Employee1, Salary1
Employee2, Salary2
.
.
.

Now, to put this in a Python Dictionary, how can we do it? Think about it. Maybe use loops? Maybe type it out manually? Think through.

We will use Dictionary comprehension and some cool Python funcionality to get this real quick. The format of a Dictionary comprehension is:

{<expression in the form 'key: value'> for <value> in <iterable>}.

We can use the csv package available in Python.

import csv
with open("employee.csv","rt") as f:
    print {row[0]: int(row[1]) for row in csv.reader(f)}

Well, this could be more clear as the readable format doesn't look so good. Let's try this:

with open("employee.csv","rt") as f:
    print {employee: int(salary) for employee, salary in csv.reader(f)}

This looks much better! To understand further, this is how it would look like in a usual loop:

with open("employee.csv","rt") as f:
    employeeDictionary = {}
    for row in csv.reader(f):
        employee = row[0]    # -> These two lines are like:
        salary = row[1]     # -> employee, salary in csv.reader(f)
        employeeDictionary[name] = int(salary)

Note: employee, salary = row is also considered to be a valid operation. a,b = [1,2] assigns a = 1 and b = 2.

Just like List comprehension, even Dictionary comprehension has the option of adding a condition:

{<expression in the form 'key: value'> for <value> in <iterable> if <condition>}.

This could be used in an example like this:

with open("employee.csv","rt") as f:
    print {employee: int(salary) for employee, salary in csv.reader(f) if employee[:4] != 'Alex'}

The above example just states that apart from Alex, all the other employees should be shown in output.

Side Note:

The usual way to open a file in Python is this:

f = open("employee.csv", "rt") # -> f is the file handler, that helps us in handling the file throughout the code
# Perform any functions with the file handler f
f.close() # -> Close the file handler once the task is done

There is a better way to do this using Python:

with open("employee.csv", "rt") as f:
    # Perform any functions with the file handler f

It basically opens the file, assigns the value to f, and then executes the given block of code. Quite simple! How so? Well, you don't have to remember to close the file everytime you use it. Once the scope of the program is over, the file closes by itself.

results matching ""

    No results matching ""