Lesson 49 +10 XP

Dictionaries

Dictionaries

A dictionary stores key-value pairs. It's like a real dictionary: you look up a word (key) and find its meaning (value).

Create a dictionary

thisdict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
print(thisdict)

Dictionary properties

  • Ordered: since Python 3.7, items keep their insertion order.
  • Changeable: add, remove, and change items freely.
  • No duplicates: keys must be unique. A later duplicate key overwrites the earlier one.
thisdict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964,
    "year": 2020
}
print(thisdict["year"])  # 2020

Access a value by key

print(thisdict["brand"])   # Ford
print(thisdict.get("brand")) # Ford

get() is safer: it returns None (or a default) instead of erroring when the key is missing.

Length

print(len(thisdict))  # 3

Keys must be hashable

Strings, ints, and tuples are fine. Lists are not.

TL;DR

  • Dictionaries use {key: value}.
  • Ordered, changeable, unique keys.
  • Access with dict[key] or the safer dict.get(key).
  • Keys must be hashable; lists can't be keys.