Dictionaries

25 min In Progress

Learning Objectives

  • Store key-value pairs
  • Access, add, and remove items
  • Iterate over dictionaries

Creating Dictionaries

Dictionaries store data as key-value pairs for fast lookup.

person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}
print(person["name"])

Modifying Dictionaries

Add, update, and remove keys easily.

person = {"name": "Alice", "age": 30}
person["age"] = 31
person["job"] = "Engineer"
del person["age"]
print(person)

Course Example: Dictionary Masher

Merge two dictionaries, keeping only new keys from the second.

def dictionary_masher(dict_a, dict_b):
  for key, value in dict_b.items():
    if key not in dict_a:
      dict_a[key] = value
  return dict_a

a = {"x": 1, "y": 2}
b = {"y": 99, "z": 3}
print(dictionary_masher(a, b))

Course Example: Sentence Analyzer

Count the occurrences of each character in a sentence.

def sentence_analyzer(sentence):
  solution = {}
  for char in sentence:
    if char is not ' ':
      if char in solution:
        solution[char] += 1
      else:
        solution[char] = 1
  return solution

print(sentence_analyzer("hello world"))

📝 Exercise: Phone Book

Create a dictionary with three names and phone numbers. Write a function lookup(name) that returns the number or 'Not found'.

code.py
Output

            
← Back to Chapter