Using Dictionaries to Store Structured DataΒΆ
The values in a dictionary can be lists. This is convenient if we would like use a dictionary to store records of some type. In this case, we can imagine the keys of the dictionary as indicating columns in a table.
employee_dict = {
'EID': [103, 105, 101, 106, 108],
'Name': ['Anna', 'Beth', 'Craig', 'Drew', 'Emma'],
'Salary': [43700, 50250, 47600, 39800, 38750],
'Rank': [2, 1, 1, 2, 3]
}
Each key in the dictionary represents a particular type of information. The associated value is a list that represents this piece of information for each record (row) in our table.
print(employee_dict['Name'])
['Anna', 'Beth', 'Craig', 'Drew', 'Emma']
If we want to see the information for a specific entry in the table, we can provide the same index to each of the lists stored within the dictionary.
print('EID Name Salary Rank')
print('---------------------------------')
for i in range(len(employee_dict['Name'])):
e = employee_dict['EID'][i]
n = employee_dict['Name'][i]
s = employee_dict['Salary'][i]
r = employee_dict['Rank'][i]
print(f'{e:<6}{n:<8}{s:<8}{r:>4}')
EID Name Salary Rank
---------------------------------
103 Anna 43700 2
105 Beth 50250 1
101 Craig 47600 1
106 Drew 39800 2
108 Emma 38750 3
One limitation of using a dictionary in this way is that there is no convenient way to extract all of the information related to a single individual at once.
As an alternate approach to using dictionaries to store structured data, we can store individual records in dictionaries, and then collect them together into a list (or another dictionary). In the setup, we could imaging the dictionaries as representing rows in a table rather than columns.
my_cats = [
{
'name':'Luna',
'birthplace':'State College, PA',
'weight':14.3,
'age':11,
'characteristics':['lazy', 'hungry', 'cranky']
},
{
'name':'Garbanzo',
'birthplace':'State College, PA',
'weight':8.9,
'age':11,
'characteristics':['talkative', 'friendly', 'skittish']
},
{
'name':'Cauchy',
'birthplace':'St. Louis, MO',
'weight':10.6,
'age':4,
'characteristics':['insane', 'destructive', 'scoundrel']
}
]
We will display the contents of the list above by looping over the dictionaries contained inside of it. We will use an f-string to print the values stored in each of the dictionaries.
print(f'{"Name":<12}{"Birthplace":<20}{"Weight":>6}{"Age":>6} {"Characteristics":<10}')
print('-'*85)
for cat in my_cats:
n = cat['name']
b = cat['birthplace']
w = cat['weight']
a = cat['age']
c = cat['characteristics']
print(f'{n:<12}{b:<20}{w:>6}{a:>6} {str(c):<10}')
Name Birthplace Weight Age Characteristics
-------------------------------------------------------------------------------------
Luna State College, PA 14.3 11 ['lazy', 'hungry', 'cranky']
Garbanzo State College, PA 8.9 11 ['talkative', 'friendly', 'skittish']
Cauchy St. Louis, MO 10.6 4 ['insane', 'destructive', 'scoundrel']