Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære for loop (5/5) | Loops
Learn Python from Scratch

book
for loop (5/5)

We haven't already discussed how can we use for loop to iterate over dictionaries, as this data structure completely differs from others. If you try to iterate just over a dictionary, it will iterate over its keys. So, it's the same that iterating over dict.keys().

In the previous section we saved countries as a dictionary too. And this time it will be much understandable how to print information. Let's see

# data
countries_dict = {'USA': (9629091, 331002651), 'Canada': (9984670, 37742154), 'Germany': (357114, 83783942)}
countries_dict["Brazil"] = (8515767, 212559417)
countries_dict["India"] = (3166391, 1380004385)

# for loop
for i in countries_dict.keys():
print("Country name:", i)
print("Area:", countries_dict[i][0])
print("Population:", countries_dict[i][1])
print("---------")
1234567891011
# data countries_dict = {'USA': (9629091, 331002651), 'Canada': (9984670, 37742154), 'Germany': (357114, 83783942)} countries_dict["Brazil"] = (8515767, 212559417) countries_dict["India"] = (3166391, 1380004385) # for loop for i in countries_dict.keys(): print("Country name:", i) print("Area:", countries_dict[i][0]) print("Population:", countries_dict[i][1]) print("---------")
copy

There key was country name and respective value - is a tuple with area and population. You see, that this for loop is much "friendlier" than the previous ones.

Oppgave

Swipe to start coding

Using the same approach, print each person's name, age, and height from people_d dictionary.

Løsning

# people dictionary
people_d = {'Alex': (23, 178), 'Noah': (34, 189), 'Peter': (29, 175)}
people_d["John"] = (41, 185)
people_d["Michelle"] = (35, 165)

# construct for loop to print information about people
for i in people_d.keys():
print("Name:", i)
print("Age:", people_d[i][0])
print("Height:", people_d[i][1])
print("---------")

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 6. Kapittel 7
single

single

# people dictionary
people_d = {'Alex': (23, 178), 'Noah': (34, 189), 'Peter': (29, 175)}
people_d["John"] = (41, 185)
people_d["Michelle"] = (35, 165)

# construct for loop to print information about people
for i in _ _ _._ _ _():
print("Name:", _ _ _)
print("Age:", _ _ _[][])
print("Height:", _ _ _[][])
print("---------")

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt