#create 40 teams.
for team_num in range(40):
new_team = {‘color’: ‘red’, ‘scores’: 3, ‘position’:
‘middle’}
teams.append(new_team)
#display the first 6 teams.
for team in teams[:6]:
print[team]
print[“…”]
#display the number of teams
we have in our dictionary
print(f “Total teams available in our list: {len(teams)}”)
In this example, we began by creating an empty list comprising of all teams
to be created in our dictionary. We use the range() method to determine the
number of times the loop will repeat. Whenever the loop goes through the
range() method, it creates a new team and appends the new team to our list
“teams.” In the line “for team in teams [:6]:”, we use
a slice to print our first
six teams. Finally, the last statement prints the length of the teams, which in
this case is 40 teams.
{‘color’: ‘red,’ ‘scores’: 3, ‘position’: ‘middle’}
{‘color’: ‘red,’ ‘scores’: 3, ‘position’: ‘middle’}
{‘color’: ‘red,’ ‘scores’: 3, ‘position’: ‘middle’}
{‘color’: ‘red,’ ‘scores’: 3, ‘position’: ‘middle’}
{‘color’: ‘red,’ ‘scores’: 3, ‘position’: ‘middle’}
{‘color’: ‘red,’ ‘scores’: 3, ‘position’: ‘middle’}
…
Total teams available in our list:40
If you observe, the teams all have the same features – color, scores, and
positions. However, it doesn’t mean that Python sees them as one item
rather a separate object. With this, we can modify any team of our choice
without affecting the other.
How possible is it to work with a collection of teams like we have?
Assuming a particular team decides to change their color and scores, how
can you do this? If you decide to change the color of a team, you can use
the “for loop” conditional test with an if statement. For instance, let us
change the first four teams' colors to black, scores to 5, and position to
center.
#Create an empty list to store the teams.
teams =[]
#create 40 teams.
for team_num in range(40):
new_team = {‘color’: ‘red’, ‘scores’: 3, ‘position’:
‘middle’}
teams.append(new_team)
for team in teams[:4]:
if team[‘color’] == ‘red’”
team[‘color’] = ‘black’
team [‘scores’] = 5
team [‘middle] = ‘center’
#display the first 6 teams.
for team in teams[:6]:
print[team]
print[“…”]
#display the number of teams we have in our dictionary
print(f “Total teams available in our list: {len(teams)}”)
When
you run the program, your output should be:
{‘color’: ‘black,’ ‘scores’: 5, ‘position’: ‘center}
{‘color’: ‘black,’ ‘scores’: 5, ‘position’: ‘center’}
{‘color’: ‘black,’ ‘scores’: 5, ‘position’: ‘center’}
{‘color’: ‘black,’ ‘scores’: 5, ‘position’: ‘center’}
{‘color’: ‘red,’ ‘scores’: 3, ‘position’: ‘center’}
{‘color’: ‘red,’ ‘scores’: 3, ‘position’: ‘center’}
…
Total teams available in our list:40
Do'stlaringiz bilan baham: