How to loop over python dictionaries and Numpy arrays

Premium

In the previous lessons, we learned about how to loop over lists. In this lesson, we will learn about how to loop over python dictionaries and Numpy arrays.

Loop over dictionaries

To loop over a dictionary elements, we use the items() method provided with a dictionary object. Let's say we have the following dictionary containing the a list of stocks along with their prices.

1portfolio = {"GOOGL":849, "FB":136, "MSFT":64, "AAPL":136, "AMZN":848}
2

As you can see, the dictionary contains key-value pairs of stock symbols and their prices. We can iterate over it and print each stock's information on a different line as follows (using for loop).

1for key, value in portfolio.items() :
2    print("The stock " + key + " has a price of " + str(value))
3

Results:

1The stock GOOGL has a price of 849
2The stock FB has a price of 136
3The stock MSFT has a price of 64
4The stock AAPL has a price of 136
5The stock AMZN has a price of 848
6

Loop Over Numpy Array (1d)

If we have a one-dimensional Numpy array, looping over it is easy. Consider the following Numpy array:

prices = np.array([5,8,12.7,89.6,12.9,5.4])

We can iterate over the elements as follows:

1import numpy as np
2prices = np.array([5,8,12.7,89.6,12.9,5.4])
3for price in prices :
4    print ("The price is: " + str(price))
5

Results:

1The price is: 5.0
2The price is: 8.0
3The price is: 12.7
4The price is: 89.6
5The price is: 12.9
6The price is: 5.4
7

Loop over Numpy Arrays (Multi-dimensional)

For multidimensional arrays, iteration proceeds over the first axis such that each loop returns a subsection of the array. Consider the following array:

1a = np.array([[ 1.,  2.,  3.],
2       [ 4.,  5.,  6.]])
3

The result will be:

1[ 1.  2.  3.]
2[ 4.  5.  6.]
3

However, if you wanted to iterate over each separate element of the multi-dimensional array, you can do so using the nditer() method as shown below:

This will print each element separately as shown below:

11.0
22.0
33.0
44.0
55.0
66.0
7

Let's take another example. Consider an array which contains original loan amounts and the balance principal outstanding on 5 different stocks. All figures are in '000.

1loan_summary = np.array([[25,10],[30,15],[30,18],[60,30],[40,7]])
2

Suppose we want to print the results in this manner - "Y principal outstanding on a loan of X". To do so, we can use multiple assignments as shown below:

1for (x, y) in loan_summary:
2    print (str(y) + " principal outstanding on a loan of " + str(x))
3

Results:

110 principal outstanding on a loan of 25
215 principal outstanding on a loan of 30
318 principal outstanding on a loan of 30
430 principal outstanding on a loan of 60
57 principal outstanding on a loan of 40
6

Exercise

Consider our loan example, but this time as a list with each item of the list containing three pieces of information: the borrower's name, the original loan amount, and the principal outstanding.

1# Loan details
2loans = [["John", 25,10],
3         ["Ken", 30,15],
4         ["Mat", 30,18],
5         ["Ron", 60,30],
6         ["David", 40,7]]
7

You need to build a for loop from scratch and print each loan's information in a separate line in this format - "'Name's took a loan of X. The outstanding balance is Y".

Hint: If your for loop is defined as:

1for loan in loans :
2    ...
3

You can use loan[0] to access the first element, loan[0] to access the second element and so on. Feel free to discuss the problem in the forum/comments.