Loop over a list of dictionaries

Tags
Summary

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.

Situation

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.

Action

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.

  1. ingredient_inventory = [
  2.     {
  3.         "ingredient_key": "beans",
  4.         "amount": 5
  5.     },
  6.     {
  7.         "ingredient_key": "egg",
  8.         "amount": 4
  9.     },
  10.     {
  11.         "ingredient_key": "flour",
  12.         "amount": 5
  13.     },
  14.     {
  15.         "ingredient_key": "gelatin-agar",
  16.         "amount": 2
  17.     },
  18.     {
  19.         "ingredient_key": "honey",
  20.         "amount": 4
  21.     },
  22.     {
  23.         "ingredient_key": "lychee",
  24.         "amount": 3
  25.     },
  26.     {
  27.         "ingredient_key": "nut",
  28.         "amount": 4
  29.     },
  30.     {
  31.         "ingredient_key": "sugar",
  32.         "amount": 4
  33.     },
  34.     {
  35.         "ingredient_key": "tea",
  36.         "amount": 4
  37.     },
  38.     {
  39.         "ingredient_key": "vanilla",
  40.         "amount": 2
  41.     }
  42. ]
  43. total_items = 0
  44. low_inventory_count = 0
  45. for ingredient in ingredient_inventory:
  46.     total_items += ingredient['amount']
  47.     if ingredient['amount'] < 3:
  48.         low_inventory_count +=1
  49.         print('Low inventory for', ingredient['ingredient_key'])
  50. average_items = total_items/len(ingredient_inventory)
  51. print('Total items:', total_items)
  52. print('Average items per ingredient type:', average_items)
  53. 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.

Where referenced