Loop Data Structures Part 1

Intermediate Python

Hugo Bowne-Anderson

Data Scientist at DataCamp

Dictionary

for var in seq :
    expression

dictloop.py

world = { "afghanistan":30.55,
          "albania":2.77, 
          "algeria":39.21 }

for key, value in world : print(key + " -- " + str(value))
ValueError: too many values to 
            unpack (expected 2)
Intermediate Python

Dictionary

for var in seq :
    expression

dictloop.py

world = { "afghanistan":30.55,
          "albania":2.77, 
          "algeria":39.21 }

for key, value in world.items() : print(key + " -- " + str(value))
algeria -- 39.21
afghanistan -- 30.55
albania -- 2.77
Intermediate Python

Dictionary

for var in seq :
    expression

dictloop.py

world = { "afghanistan":30.55,
          "albania":2.77, 
          "algeria":39.21 }

for k, v in world.items() : print(k + " -- " + str(v))
algeria -- 39.21
afghanistan -- 30.55
albania -- 2.77
Intermediate Python

NumPy Arrays

for var in seq :
    expression

nploop.py

import numpy as np
np_height = np.array([1.73, 1.68, 1.71, 1.89, 1.79])
np_weight = np.array([65.4, 59.2, 63.6, 88.4, 68.7])

bmi = np_weight / np_height ** 2
for val in bmi : print(val)
21.852
20.975
21.750
24.747
21.441
Intermediate Python

2D NumPy Arrays

nploop.py

import numpy as np
np_height = np.array([1.73, 1.68, 1.71, 1.89, 1.79])
np_weight = np.array([65.4, 59.2, 63.6, 88.4, 68.7])
meas = np.array([np_height, np_weight])

for val in meas : print(val)
[ 1.73  1.68  1.71  1.89  1.79]
[ 65.4  59.2  63.6  88.4  68.7]
Intermediate Python

2D NumPy Arrays

nploop.py

import numpy as np
np_height = np.array([1.73, 1.68, 1.71, 1.89, 1.79])
np_weight = np.array([65.4, 59.2, 63.6, 88.4, 68.7])
meas = np.array([np_height, np_weight])

for val in np.nditer(meas) : print(val)
1.73
1.68
1.71
1.89
1.79
65.4
...
Intermediate Python

Recap

  • Dictionary
    • for key, val in my_dict.items() :
  • NumPy array
    • for val in np.nditer(my_array) :
Intermediate Python

Let's practice!

Intermediate Python

Preparing Video For Download...