Dictionaries

Calvin (Deutschbein)

W11Mon: 04 Nov

Announcements

  • Project 3 tonight.
  • Midterm Friday.
    • Practice Exam posted.
    • Tuples
    • Pixels
    • Lists
    • Types

Today

  • Dictionaries
    • Dictionaries and Maps
    • Editorializing
    • Keys and Values
    • In and Indices
    • Iteration
    • Methods

Maps and Dictionaries

  • A common form of information associates pairs of data values
    • Commonly called a map in computer science
    • Python calls such a structure a dictionary
    • I learned them as "hash tables"

Maps and Dictionaries

  • A dictionary associates two different values:
    • A simple value called the key, which is often a string but doesn’t need to be
    • A larger and more complex object called the value

Maps and Dictionaries

  • This idea of associating pairs of values is exhibited all over in the real world
    • Actual dictionaries! The words are the keys, the definitions the values.
    • Web addresses! Keys are the urls, the values are the webpage contents.
    • Humans! Keys are names, values are the actual people.

Creating Dictionaries

  • Python dictionaries use squiggly brackets {} to enclose their contents

  • Can create an empty dictionary by providing no key-value pairs:

    d = {}
  • Or via "dict()" (like list(), int(), etc)

    d = dict()
  • Separate keys from values with colons, separate key-value pairs from pairs with commas. skewlz = {'Willamette': "Bearcat", "Carolina": "Tarheel", "Chicago:": "Phoenix"}

Creating Dictionaries

  • We look up values using a key: >>> skewlz = {'Willamette': "Bearcat", "Carolina": "Tarheel", "Chicago:": "Phoenix"} >>> skewlz["Carolina"] 'Tarheel' >>> skewlz["Willamette"] 'Bearcat'

Today

  • Dictionaries
    • ✓ Dictionaries and Maps
    • Editorializing
    • Keys and Values
    • In and Indices
    • Iteration
    • Methods

Editorializing

  • Known class-hater Calvin Deutschbein approves of maps.
    • "Map" is a functional idea, the not-class style of things
    • Google, and latter other cloud provides, use maps heavily.
      • That is, in 2024, I expect the preponderance of computing to take place within a map framework.
    • Maps seems very close to human reasoning in my impression.
    • Consider - have you used a map? A dictionary?
    • How a an object instantied from some class?

Editorializing

  • My brain works in maps.
    • When I met you in the early weeks of class, I was learning keys.
      • I learned to spell your name, where you commonly sat, etc.
    • Now I've learned more about you as people!
    • Because of who I am as a person, I historically struggled with e.g. names, but...
    • I programmed my brain with maps.
    • Thank you for helping me!

Today

  • Dictionaries
    • ✓ Dictionaries and Maps
    • ✓ Editorializing
    • Keys and Values
    • In and Indices
    • Iteration
    • Methods

Keys and Values

  • The value of a key-value pair can be any Python object, mutable or immutable
    • This include other dictionaries!
  • The key is more restricted:
    • Must be immutable
      • So dictionaries or lists can not work as a key
      • Tuples can though!
    • Must be unique per dictionary
    • >>> d = {"Fav Prof":"Calvin", "Fav Prof":"Anyone else"} >>> d {'Fav Prof': 'Anyone else'}

Keys and Values

  • Must be unique per dictionary
  • >>> d = {"Fav Prof":"Calvin", "Fav Prof":"Anyone else"} >>> d {'Fav Prof': 'Anyone else'}
  • Setting a key to have some value overwrites the previous value.
    • Same as updating a variable
    • Same as updating an attribute of a class.
    • Same as updating an element of a list at some index.
  • Wait... are Python variables... key-value pairs? (yes)

Today

  • Dictionaries
    • ✓ Dictionaries and Maps
    • ✓ Editorializing
    • ✓ Keys and Values
    • In and Indices
    • Iteration
    • Methods

Selection

  • The fundamental operation on dictionaries is selection, which is indicated with square brackets just like list/string/tuple: []

  • Dictionaries though are unordered, so it is not a numeric index
  • You instead use the key directly to select corresponding values:

    >>> movie = {"Franchise" : "Alien", "Entry": "Romulus"} >>> movie["Entry"] 'Romulus'

Non-numeric keys

  • With strings/lists/tuples we trivially knew what indices existed based on length.
  • Dictionaries are more complicated.
  • If you attempt to index out a key that doesn’t exist: >>> movie["anything bad"] Traceback (most recent call last): File "<stdin>", line 1, in KeyError: 'anything bad'
  • Wow! There is not "anything bad" in Alien: Romulus!

Non-numeric keys

  • If in doubt, check for the presence of a key with the special operator 'in'
    • Recall we used "in" many times with strings, like: 'ei' in word and 'cei' not in word
  • With dictionaries, we can if keys are 'in': >>> movie = {"Franchise" : "Alien", "Entry": "Romulus"} >>> "anything bad" in movie False >>> "Year" in movie True >>> "Franchise" in movie True

Non-numeric keys

  • Look out!
  • In strings/list/tuples, "in" checks values - the things that have an index.
  • In dictionaries, it checks the keys, not the values! >>> "Alien" in movie False >>> "Franchise" in movie True >>> movie["Franchise"] 'Alien'

Non-numeric keys

  • We can update values.
  • Some critics consider Alien: Romulus part of the larger "Alien vs Predator" franchise
  • They are wrong, but still deserve rights.
  • We can falsify our data entry to sate the Predator fanbase >>> movie = {"Franchise" : "Alien", "Entry": "Romulus"} >>> movie["Franchise"] 'Alien' >>> movie["Franchise"] = "AVP" >>> movie["Franchise"] 'AVP'
  • Like the xenomorph, dictionaries may mutate.
  • (Dictionaries are mutable)

Today

  • Dictionaries
    • ✓ Dictionaries and Maps
    • ✓ Editorializing
    • ✓ Keys and Values
    • ✓ In and IndicesSelectors
    • Iteration
    • Methods

Iterating through a Dictionary

  • I love for loops.
  • for key in movie: value = movie[key] print("The", key, "of the movie is", value)
  • This would give us, for example: The Franchise of the movie is Alien The Entry of the movie is Romulus

Iterating through a Dictionary

  • Like zip() and enumerate(), we have a bundle of tricks to look at indiceskeys and values at the same time. for key, value in movie.items(): print("The", key, "of the movie is", value)
  • This would give us, for example: The Franchise of the movie is Alien The Entry of the movie is Romulus

Iterating through a Dictionary

  • What is "Alien"? >>> for key, value in movie.items(): ... if value == "Alien": ... print(key) ... Franchise
  • Wow, it's "the" franchise. Incredible.
  • What a time to be alive!

Today

  • Dictionaries
    • ✓ Dictionaries and Maps
    • ✓ Editorializing
    • ✓ Keys and Values
    • ✓ In and IndicesSelectors
    • ✓ Iteration
    • Methods

Common Dictionary Methods

    Method call Description
    len(d) Returns the number of key-value pairs in the dictionary
    d.get(key, value) Returns the value associated with the given key in the dictionary. If the key is not found, returns None
    d.pop(key) Removes the key-value pair corresponding to key and returns the associated value. Will raise an error if the key is not found.
    d.clear() Removes all key-value pairs from the dictionary, leaving it empty.
    d.items() Returns an iterable object that cycles through the successive tuples consisting of a key-value pair. Iterables are weird - either use this within a for loop, or convert it to a list with list()

Editorializing Again

  • My take on classes is a minority position.
  • Another take: Dictionaries are the "Pythonic" way to do records.
  • I find this to be a is a majority position,
  • It is held by major language designers and most programers that use the language heavily.
  • Looks at this: console = { 'name': 'XBox', 'vers': 360, }
  • It is impossible for me to believe that isn't better than writing a class.

Today

  • ✓ Dictionaries
    • ✓ Dictionaries and Maps
    • ✓ Editorializing
    • ✓ Keys and Values
    • ✓ In and IndicesSelectors
    • ✓ Iteration
    • ✓ Methods

Announcements

  • Project 3 tonight.
  • Midterm Friday.
    • Practice Exam posted.
    • Tuples
    • Pixels
    • Lists
    • Types