Dictionaries

Intermediate Python for Finance

Kennedy Behrman

Data Engineer, Author, Founder

Lookup by index

my_list = ['a','b','c','d']
  0   1   2   3
['a','b','c','d']
my_list[0]
'a'
my_list.index('c')
2
Intermediate Python for Finance

Lookup by key

Dictionaries

Diagram of keys pointing to values

Intermediate Python for Finance

Representation

{ 'key-1':'value-1', 'key-2':'value-2', 'key-3':'value-3'}
Intermediate Python for Finance

Creating dictionaries

my_dict = {}
my_dict
{}
my_dict = dict()
my_dict
{}
Intermediate Python for Finance

Creating dictionaries

ticker_symbols = {'AAPL':'Apple', 'F':'Ford', 'LUV':'Southwest'}
print(ticker_symbols)
{'AAPL':'Apple', 'F':'Ford', 'LUV':'Southwest'}
ticker_symbols = dict([['APPL','Apple'],['F','Ford'],['LUV','Southwest']])
print(ticker_symbols)
{'AAPL':'Apple', 'F':'Ford', 'LUV':'Southwest'}
Intermediate Python for Finance

Adding to dictionaries

ticker_symbols['XON'] = 'Exxon'
ticker_symbols
{'APPL': 'Apple', 'F': 'Ford', 'LUV': 'Southwest', 'XON': 'Exxon'}
ticker_symbols['XON'] = 'Exxon OLD'
ticker_symbols
{'APPL': 'Apple','F': 'Ford','LUV': 'Southwest','XON': 'Exxon OLD'}
Intermediate Python for Finance

Accessing values

ticker_symbols['F']
'Ford'
Intermediate Python for Finance

Accessing values

ticker_symbols['XOM']
KeyError                                  Traceback (most recent call last)
<ipython-input-6-782fbf617bf7> in <module>()
-> 1 ticker_symbols['XOM']

   KeyError: 'XOM'
Intermediate Python for Finance

Accessing values

company = ticker_symbols.get('LUV')
print(company)
'Southwest'
company = ticker_symbols.get('XOM')
print(company)
None
company = ticker_symbols.get('XOM', 'MISSING')
print(company)
'MISSING'
Intermediate Python for Finance

Deleting from dictionaries

ticker_symbols
{'APPL': 'Apple', 'F': 'Ford', 'LUV': 'Southwest', 'XON': 'Exxon OLD'}
del(ticker_symbols['XON'])
ticker_symbols
{'APPL': 'Apple', 'F': 'Ford', 'LUV': 'Southwest'}
Intermediate Python for Finance

Let's practice!

Intermediate Python for Finance

Preparing Video For Download...