Dictionaries Lists
1 2 3 4 5 6 7 |
my_list = ['a','b','c','d'] # index 0 1 2 3 my_list[0] > 'a' my_list.index['c'] > 2 |
Intro
1 2 3 4 5 |
Keys Values ---- ------ Firm Code FRD Process Date 10/14/2019 CUSIP 13246879 |
Representation of a dictionary = { ‘key-1’ : ‘value-1’ , ‘key-2’ : ‘value-2’ , ‘key-3’ : ‘value-3’ , ‘key-4’ : ‘value-4’ } Creation
1 2 3 4 5 6 7 8 9 10 11 |
# Create an empty dict my_dict = {} my_dict > {} # native tickersymbols = {'AAPL':'Apple', 'F':'Ford', 'XON':'Exxon'} > {'AAPL': 'Apple', 'F': 'Ford', 'XON': 'Exxon'} # OR by lists tickersymbols = dict([['AAPL','Apple'],['F','Ford'],['XON','Exxon']]) > {'AAPL': 'Apple', 'F': 'Ford', 'XON': 'Exxon'} |
Handling a dictionary
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Adding tickersymbols['TSLA'] = 'Tesla' tickersymbols > {'AAPL': 'Apple', 'F': 'Ford', 'XON': 'Exxon', 'TSLA': 'Tesla'} # Update tickersymbols['TSLA'] = 'Tesla_Inc' tickersymbols > {'AAPL': 'Apple', 'F': 'Ford', 'XON': 'Exxon', 'TSLA': 'Tesla_Inc'} # Deleting an entry del(tickersymbols['F']) tickersymbols > {'AAPL': 'Apple', 'XON': 'Exxon', 'TSLA': 'Tesla_Inc'} |
Accessing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Entry in dict tickersymbols['XON'] > 'Exxon' # No entry in dict tickersymbols['IBM'] > KeyError: 'IBM' # Second method tickersymbols.get('XON') > 'Exxon' tickersymbols.get('IBM') > (nothing) tickersymbols.get('IBM','Missing ticker') > 'Missing ticker' |
Examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
from datetime import datetime, timedelta alphabet_hist = {datetime.datetime(2019, 7, 30, 0, 0): 1228, datetime.datetime(2019, 7, 31, 0, 0): 1218.2, datetime.datetime(2019, 8, 1, 0, 0): 1211.78, datetime.datetime(2019, 8, 2, 0, 0): 1196.32} closing_price_date = datetime.datetime(2019, 8, 2, 0, 0) # Closing price for day before day_before_closing_price_date = closing_price_date - timedelta(days=1) # Safely print closing price day before or None if it's missing print(alphabet_hist.get(day_before_closing_price_date)) > 1211.78 # Get day eight weeks in future future_closing_price_date = closing_price_date + timedelta(weeks=8) # Safely get value for the future date or the string 'Missing' print(alphabet_hist.get(future_closing_price_date, 'Missing')) > Missing # Print with key print(alphabet_hist) > {datetime.datetime(2019, 8, 2, 0, 0): 1196.32, datetime.datetime(2019, 8, 1, 0, 0): 1211.78, datetime.datetime(2019, 7, 31, 0, 0): 1218.2, datetime.datetime(2019, 7, 30, 0, 0): 1228} # Remove entry del(alphabet_hist[closing_price_date]) # Print with key deleted print(alphabet_hist) > {datetime.datetime(2019, 8, 1, 0, 0): 1211.78, datetime.datetime(2019, 7, 31, 0, 0): 1218.2, datetime.datetime(2019, 7, 30, 0, 0): 1228} |