intro to dictionaries (slides)

CSc 110 - dictionaries

Announcements

  • Last lab for short project 06 is Today – no lab this week, we re-start lab sessions Tuesday Mar 18

Data Structure

  • A data-structure is a way of arranging and organizing data in a computer program

  • Python has several useful data-structures built into the language

    • One is a list (already covered)

    • Another, dictionary

Mapping

  • Many data structures allow data to be stored and retrieved using a concept called mapping

  • Mapping is the process of associating one value with another (a key with a value)

    • Sometimes also referred to as Hashing or Associativity

Mapping

  • Lists map keys to values too!

    • Indices of the list are the keys

    • Elements in the list are the values

  • Keys (indices) are used to acess or modify the elements in the list

Mapping and Lists

numbers = [12, 49, -2, 26, 5, 17, -6]

# Using the key 3 to lookup the associated value of 26
# and then save the value into variable
new = numbers[3]

# Modifying the list so that the key 5 now maps to 77
# instead of 17
numbers[5] = 77

Dictionary

  • Like lists:

    • Associates a set of keys to their corresponding values
    • Each key has exactly 1 associated value
  • Unlike lists:

    • The keys can be types other than ints: strings

Dictionary

Example (mapping strings to integers)

singers = { "Taylor Swift": 1989,
            "JVKE":  2001,
            "Bruno Mars":  1983}
        
# Using the key "JVKE" 
# to lookup the number 2001
singers["JVKE"]

# Modifying the value associated with "Bruno Mars" 
singers["Bruno Mars"] = 1985

# add a new key and value pair
singers["Doja Cat"] = 1995

print(singers)
{'Taylor Swift': 1989, 'JVKE': 2001, 'Bruno Mars': 1985, 'Doja Cat': 1995}

Evaluate the expressions

word_count = {"and": 324, "why": 134, "cannot": 76, "sanded": 13}
word_count["cannot"] = 90
word_count["and"] = 110
word_count["foot"] = "feet"
word_count["and"] += 10

# what will these evaluate to?
word_count["and"] 
word_count["cannot"]
word_count["foot"]

Evaluate the expressions

word_count = {"and": 324, "why": 134, "cannot": 76, "sanded": 13}
word_count["cannot"] = 90
word_count["and"] = 110
word_count["foot"] = "feet"
word_count["and"] += 10

# what will these evaluate to?
word_count["and"]
120
word_count["cannot"]
90
word_count["foot"]
'feet'

Attendance

Attendance Evaluate the expression on Gradescope.

Review: list methods

  • .append(value)
  • .remove(value)
  • .pop(index)

Dictionary operations

Adds a new key/value pair:

scores = {'A': 10, 'B': 25, 'C': 27, 'D': 10, 'E': 5}
scores['A+'] = 7  # key not in the original dictionary   

Changes value associated with a key:

scores['B'] = 20    # key in the dictionary

Retrieves a value:

scores['C']    

Removes a key/value pair:

scores.pop('E')      

The in operator

With strings:

"a" in "aeiou"
True

With lists:

1 in [1, 2, 3, 4, 5]
True

Check if an item is a dictionary key:

word_count = {"and": 324, "why": 134, "cannot": 76, "Sanded": 13}
"why" in word_count
True

Write a function

It returns a dictionary with the count of every vowel in the string.

Use for loop.

assert count_vowels("") == {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0}
assert count_vowels("pineapple") == {"a": 1, "e": 2, "i": 1, "o": 0, "u": 0}

Write a function – solution

def count_vowels(string):
  counts = {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0}
  for i in range(len(string)):
    char = string[i]
    if char in counts:
      counts[char] += 1
  return counts

def main():
  assert count_vowels("") == {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0}
  assert count_vowels("pineapple") == {"a": 1, "e": 2, "i": 1, "o": 0, "u": 0}
  
main()

Write a function

It returns the dictionary with the count of every characters in the string.

assert count_chars("") == {}
assert count_chars("banana") == {"b": 1, "a": 3, "n": 2}

Write a function – solution

def count_chars(string):
  counts = {}
  for i in range(len(string)):
    char = string[i]
    if char in counts:
      counts[char] += 1
    else:
      counts[char] = 1
      
  return counts

def main():
  assert count_chars("") == {}
  assert count_chars("banana") == {"b": 1, "a": 3, "n": 2}
  print("pass all test cases")

main()
pass all test cases