How to loop over python dictionaries and Numpy arrays

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.

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

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).

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

Results:

The stock GOOGL has a price of 849
The stock FB has a price of 136
The stock MSFT has a price of 64
The stock AAPL has a price of 136
The stock AMZN has a price of 848

Loop Over Numpy Array (1d)

This content is for paid members only.

Join our membership for lifelong unlimited access to all our data science learning content and resources.

Related Downloads