1 / 6

Dictionaries

Dictionaries. Alexandra Stefan CSE1310 – University of Texas at Arlington. Dictionary. A sequence of key-value pairs: { key:value , key:value ,… key: value } Optimized for efficient search based on the key May not always print the elements in the same order

breck
Download Presentation

Dictionaries

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Dictionaries Alexandra Stefan CSE1310 – University of Texas at Arlington

  2. Dictionary • A sequence of key-value pairs: {key:value, key:value,… key: value} • Optimized for efficient search based on the key • May not always print the elements in the same order • As you make modifications (insert/delete elements) the order of the pairs may change to enable fast searching

  3. Legal Keys • No duplicate keys • Cannot have multiple entries for a key • Keys must be immutable types • Strings • Integers • Tuples • Mix and match is okay Slide by Chris Conly

  4. Working with dictionaries • {key:value, key:value,… key: value} • What operations would you like? What operations do you know from the other collections?

  5. Working with dictionaries • They are mutable • Shallow copies • d = {key:value,key:value,… key: value} • Functions: • d[new_key] = new_value • del d[key] • d.items(), d.keys(), d.values() • list(d.keys()), sorted(d.keys()) • len(d): number of key-value pairs • in: verifies that a key is in the dictionary • min(__), max(__)

  6. keys(), values(), items() • They are called view objects • They reflect changes made to the dictionary • If you add or delete items in the dictionary, the views will reflect that • “If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.” – Python Standard Library • To get a list of them use the list constructor: • list(d.keys()), list(d.values()), list(d.items()) • How connected are the lists and the views they are based on? • d = {1:[1,2]}, lv = list(d.values()), d[1][0] = 10, d, lv, lv[0][1] = 200, lv, d

More Related