Lecture 22 — Dictionaries, Part 1 ================================== Overview -------- - Dictionaries and dictionary operations - Solutions to the problem of counting how many items are associated with each category in Customers.txt files - Other applications Introduction to Dictionaries ---------------------------- - Association between "keys" (like words in an English dictionary) and "values" (like definitions in an English dictionary). The values can be **anything**. - Examples: :: >>> children = dict() >>> children = {} # either of these works >>> children['Sam'] = 11 >>> children['Peter'] = 12 >>> children['Alice'] = 10 >>> children['Jon'] = 13 >>> children {'Sam': 11, 'Peter': 12, 'Alice': 10, 'Jon': 13} >>> 'Sam' in children True >>> 'Luke' in children False >>> 13 in children False >>> list(children.keys()) ['Sam', 'Peter', 'Alice', 'Jon'] >>> sorted(children.keys()) ['Alice', 'Jon', 'Peter', 'Sam'] >>> children.values() dict_values([11, 12, 10, 13]) >>> list(children.values()) [11, 12, 10, 13] - Details: - Two initializations; either would work. - Syntax is very much like the subscripting syntax for lists, except dictionary subscripting/indexing uses keys instead of integers! - The keys, in this example, are children names and the values are their age (integers). - The ``in`` method tests only for the presence of the key, like looking up a word in the dictionary without checking its definition. - The keys are NOT ordered. - Just as in sets, the implementation uses *hashing* of keys. - Conceptually, sets are dictionaries without values. Lecture Slides --------------- https://drive.google.com/file/d/1CYbKuitjXjWBKpgnljO4vr-nnuaP_gsF/view?usp=sharing Lecture Video ------------- https://www.youtube.com/watch?v=KNVhshzNeoU&t=4s