Nate Brunelle Today: Dictionaries CS1110 Nate Brunelle Today: Dictionaries
Questions?
Collections Order doesn’t matter, No Repetition Order Matters, Repetition ok Examples: String List Tuple Range Counting starts at 0 collection[index] gives a specific value in the collection Order doesn’t matter, No Repetition Examples: Set Dict Map Table
Set Things are unordered Cannot have repetition
Dict A set of key:value mappings d = { } # How we create one d[‘name’] = 1 # How we insert somthing d[‘name’] # Access something
Dict is like variables Gives names to values Create using = Reassign using = Easy to go from name to a value Very hard to go from value to name
Dict is like a List Index to access members Key to access members Key can be any immutable type No rules for values of keys To add in a new thing: d[key] = … Index to access members Index must be an int Indexes cannot be skipped To add in a new thing: lst.append(…)
Using a dict as a Collection d.keys() Gives a list of all of the keys in the dict The key is the thing in square brackets The “word” When you use a dict as a collection, it defaults to this E.g.: for thing in d d.values() Gives a list of all the values in the dict The value is what you get when you access using a key The “definition” d.items() Gives a list of all (key, value) tuples in the dict
Key Value Bananas 12.0 Gloves 29.0 Suit 100.0 Bananas 10.0 Gloves 29.0 Suit 100.0 Bananas 2.0 If that thing was in the dictionary: add to that value Else: add that thing to the dictionary, with value equal to the cost