Python 3

home

Introduction to Python

davidbpython.com




Reading Multidimensional Containers: Subscripting


pinpointing a specific value within a structure

We can use subscripts to "travel to" a value within a multidimensional.


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

val1 = value_table[0][0]       # float, 1
val2 = value_table[0][2]       # float, 3
val3 = value_table[2][2]       # float, 300






pinpointing a value 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'  }
]

val = lod[2]['lname']         # 'Smith'

val2 = lod[0]['fname']        # 'Ally'






pinpointing a value in a dict of dicts

A dict of dicts has string keys and dict values.


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

val = dod['ak23']['fname']     # 'Ally'

val2 = dod['js7']['lname']     # 'Smith'


Ex. 7.8 -> 7.10





[pr]