You have a data set. Each record is a dictionary. All the records are in a list. Use a for
loop to run through each record in the list.
You have a list. Each item is a dictionary containing a data record. All records have the same fields, like a field called weight
.
You want to do something to each element of the list, or compute something that's a characteristic of an entire list, like the total of all weight
fields.
The general form of the loop is:
- for thing in list_of_things:
- Do something with thing's fields
Here's data from a game I'm working on.
- ingredient_inventory = [
- {
- "ingredient_key": "beans",
- "amount": 5
- },
- {
- "ingredient_key": "egg",
- "amount": 4
- },
- {
- "ingredient_key": "flour",
- "amount": 5
- },
- {
- "ingredient_key": "gelatin-agar",
- "amount": 2
- },
- {
- "ingredient_key": "honey",
- "amount": 4
- },
- {
- "ingredient_key": "lychee",
- "amount": 3
- },
- {
- "ingredient_key": "nut",
- "amount": 4
- },
- {
- "ingredient_key": "sugar",
- "amount": 4
- },
- {
- "ingredient_key": "tea",
- "amount": 4
- },
- {
- "ingredient_key": "vanilla",
- "amount": 2
- }
- ]
- total_items = 0
- low_inventory_count = 0
- for ingredient in ingredient_inventory:
- total_items += ingredient['amount']
- if ingredient['amount'] < 3:
- low_inventory_count +=1
- print('Low inventory for', ingredient['ingredient_key'])
- average_items = total_items/len(ingredient_inventory)
- print('Total items:', total_items)
- print('Average items per ingredient type:', average_items)
- print('Number of ingredients with low inventory:', low_inventory_count)
Lines 1 to 42 create a list of dictionaries. Each dictionary has the same fields.
Line 45 loops over the list. The first time through the loop, ingredient
will be the first item in the list. The second time, ingredient
will be the second item in the list. And so on.
The loop will run ten times because there are ten records in the list.
Lines 46 and 48 accumulate numeric values. Line 48 only runs when the condition in line 47 is true.
len()
in line 50 returns the number of elements in the list.