Lessons
- Python Dictionaries
- Comparison Operators in Python
- Logical Operators in Python
- Conditional Statements in Python
- For Loop in Python
- While Loop in Python
- How to loop over python dictionaries and Numpy arrays
- What is NumPy in Python
- ndarray - Methods and Data Type
- NumPy - Methods to Create Arrays
- Python NumPy - Numerical Operations on Arrays
- Python NumPy - Indexing and Slicing Arrays
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.