3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) [Clang 6.0 (clang-600.0.57)] Python Type "help", "copyright", "credits" or "license" for more information. # 'Dictionary' in Python # type 'dict' # In computer science, a dictionary is a data structure that allows # us to 'look up' values using names rather than index numbers like # we did in lists. # We make a Python dictionary using curly brackets {} d = {'a': 4, 'b': 5, 'c':6} d {'a': 4, 'b': 5, 'c': 6} type(d) d['a'] 4 d['b'] 5 # Dictionaries have 'keys' and 'values' d.keys() dict_keys(['a', 'b', 'c']) d.values() dict_values([4, 5, 6]) # Each key in the dictionary has a corresponding value # The value at the key 'a' in d is 4 # We can say that we 'map keys to values' # A dict is a collection of key-value pairs d = {'a': 4, 'b': 5, 'c':6, 'a': 9} d['a'] 9 d {'a': 9, 'b': 5, 'c': 6} # IMPORTANT: Keys should be unique. d = {'a': 4, 'b': 5, 'c':4} d {'a': 4, 'b': 5, 'c': 4} # values don't have to be unique # but key do since we use them to lookup values d = {1: 4, 'b': 5, 'c':4} d[1] 4 d[2] Traceback (most recent call last): Python Shell, prompt 29, line 1 builtins.KeyError: 2 # if we don't find a key, we get a KeyError d = {1: 4, 'b': 1, 'c':4} d['b'] 1 d[1] 4 # we can only look-up with keys. can't put values in square brackets # Dictionaries don't have a predictable order like lists do d.keys() dict_keys([1, 'b', 'c']) list(d.keys()) [1, 'b', 'c'] # This order usually doesn't matter when you're working with dicts d = {1: 4, 'b': ['hello'], 'c':6} d['b'] ['hello'] d = {['csc120']: 4, 'b': ['hello'], 'c':6} Traceback (most recent call last): Python Shell, prompt 41, line 1 builtins.TypeError: unhashable type: 'list' # the word 'hash' comes from the CS term 'hash table' which # is basically the same as a dictionary # This error means that we can't use a list as a key # Using mutable types (like lists) for keys is a bad idea # since we want to ensure that the keys that we use for looking up # values don't change # So Python will just not let you do it - will give you an error # Ensure keys are immutable. # Values can be mutable d {1: 4, 'b': ['hello'], 'c': 6} id(d) 4532391800 # we can change values in place d['c'] 6 d['c'] = True d {1: 4, 'b': ['hello'], 'c': True} id(d) 4532391800 # dicts themselves are mutable id(d['b']) 4534135432 d['b'].append('csc120') d {1: 4, 'b': ['hello', 'csc120'], 'c': True} id(d['b']) 4534135432 # dictionary values that are mutable will continue to be mutable d {1: 4, 'b': ['hello', 'csc120'], 'c': True} 4 in d False 1 in d True # using 'in' looks through the keys of d 4 in d.values() True d.values() dict_values([4, ['hello', 'csc120'], True]) list(d.values()) [4, ['hello', 'csc120'], True] # To add a key to a dict, simply add it in place d['e'] = 87 d {1: 4, 'b': ['hello', 'csc120'], 'c': True, 'e': 87}