Python 3

home

Introduction to Python

davidbpython.com




Reading Multidimensional Containers: Looping


looping through a struct to read each "inner" structure

We begin by identifying the "inner" structures; 'for' looping takes us to each one in turn.


value_table =       [
                       [ 1, 2, 3 ],
                       [ 10, 20, 30 ],
                       [ 100, 200, 300 ]
                    ]

for inner_list in value_table:    # list, [ 1, 2, 3 ]

    print(inner_list[0])          # 1
                                  # 10
                                  # 100






looping through and accessing values within a list of dicts

In a list of dicts, each item is a dict.


lod = [
    { 'fname': 'Ally',
      'lname': 'Kane'   },
    { 'fname': 'Bernie',
      'lname': 'Bain'   },
    { 'fname': 'Josie',
      'lname': 'Smith'  }
]

for inner_dict in lod:
    print(inner_dict['fname'])         # Ally
    print(inner_dict['lname'])         # Kane
    print()

                                       # Bernie
                                       # Bain

                                       # Josie
                                       # Smith






looping through and accessing values within a dict of dicts

In dict of dicts, looping through retrieves each key, and we must subscript to retrieve the "inner" dict.


dod = {
    'ak23':  { 'fname': 'Ally',
               'lname': 'Kane' },
    'bb98':  { 'fname': 'Bernie',
               'lname': 'Bain' },
    'js7':   { 'fname': 'Josie',
               'lname': 'Smith' },
}

for id_key in dod:
    inner_dict = dod[id_key]

    print((inner_dict['fname']))        # Ally
    print((inner_dict['lname']))        # Kane
    print()


Ex. 7.16 -> 7.18 also to discuss building a struct from file (Ex. 7.25 -> 7.30)





[pr]