Execute Program

Python for Programmers: Dictionaries

Welcome to the Dictionaries lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • Dictionaries ("dicts") associate keys with values. For example, a user might have a name of "Amir" and an email address of "amir@example.com".

  • Dictionaries correspond to hashmaps, maps, or hashes in other languages. They're also similar to JavaScript's objects, although JavaScript's Map is an even closer equivalent.

  • >
    user = {
    "name": "Amir",
    "email": "amir@example.com",
    }
    user["name"]
    Result:
    'Amir'Pass Icon
  • Note that like with lists and tuples, the final trailing comma is optional.

  • Trying to access a key that doesn't exist raises a KeyError. This is similar to what we saw for lists, where accessing an index that doesn't exist raises IndexError.

  • >
    user = {
    "name": "Amir",
    "email": "amir@example.com",
    }
    user["age"]
    Result:
    KeyError: 'age'Pass Icon
  • We can change a dict key's value by assigning to it, using the same syntax that we use for lists. We can also add new keys by assigning directly to them. That's different from lists, where assigning to an index that doesn't exist is an error.

  • >
    user = {
    "name": "Amir",
    "email": "amir@example.com",
    }
    user["age"] = 36
    user
    Result:
  • We can delete dictionary items with del some_dict[some_key]. "Item" refers to the entire key-value pair. When we delete an item, we're deleting both the key and its value.

  • >
    user = {
    "name": "Amir",
    "email": "amir@example.com",
    }
    del user["email"]
    user
    Result:
    {'name': 'Amir'}Pass Icon
  • If we try to remove a key that doesn't exist, Python raises a KeyError.

  • >
    user = {
    "name": "Amir",
    "email": "amir@example.com",
    }
    del user["age"]
    user
    Result:
    KeyError: 'age'Pass Icon
  • If you know JavaScript, dictionaries may seem like an equivalent of JavaScript's objects. However, dictionaries are much more powerful!

  • All JavaScript object keys must be strings, numbers, or symbols (which are a string-like data type in JavaScript). Python's dictionaries allow many more data types as dictionary keys. That even includes some compound types like tuples, not just simple types like numbers or booleans.

  • >
    treasure_locations = {
    (4, 5): "diamonds",
    (12, 7): "silver",
    (8, 23): "gold",
    }
    treasure_locations[(12, 7)]
    Result:
    'silver'Pass Icon
  • We can mix different key types in one dictionary, like numbers and strings. They won't collide even if the values look superficially similar, like 1 vs. "1". Those are different values, so they result in different dict items.

  • >
    some_dict = {
    "1": "a",
    1: "b",
    }
    [some_dict[1], some_dict["1"]]
    Result:
    ['b', 'a']Pass Icon
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    some_dict
    Result:
    {'1': 'a', 1: 'b'}Pass Icon
  • We've used value in some_list to decide whether a list contains a value. That also works with dictionaries: some_key in some_dict decides whether the dictionary contains that key.

  • >
    some_dict = {
    "a": 1,
    }
    "a" in some_dict
    Result:
    TruePass Icon
  • >
    some_dict = {
    "a": 1,
    }
    "b" in some_dict
    Result:
    FalsePass Icon
  • The not in operator also works with dicts.

  • >
    some_dict = {
    "a": 1,
    }
    "b" not in some_dict
    Result:
    TruePass Icon
  • Although we can use in to check for keys, we can't use it to check for values. The in operator only searches keys.

  • >
    some_dict = {
    "a": 1,
    }
    1 in some_dict
    Result:
    FalsePass Icon
  • We can get a dictionary's keys with the .keys() method.

  • >
    some_dict = {
    "a": 1,
    "b": 2,
    }
    list(some_dict.keys())
    Result:
    ['a', 'b']Pass Icon
  • In that example, we explicitly converted the keys into a list with list(...). That's because .keys() returns a view object, which isn't a list. View objects are a kind of iterable, which means "things that we can iterate over". We'll cover them in detail in a later lesson.

  • We can also get a dictionary's keys by calling list(some_dict). However, .keys() is generally preferable because it's more explicit.

  • >
    some_dict = {
    "a": 1,
    "b": 2,
    }
    list(some_dict)
    Result:
    ['a', 'b']Pass Icon
  • To get a dictionary's values, we can use the .values() method. We'll convert it into a list for the same reason explained above.

  • >
    some_dict = {
    "a": 1,
    "b": 2,
    }
    list(some_dict.values())
    Result:
    [1, 2]Pass Icon
  • In those examples, the keys and values came out in the same order that we defined them. That's not a coincidence! Python dictionaries remember their items' insertion order, no matter how the items were inserted.

  • >
    some_dict = {}
    some_dict["b"] = 2
    some_dict["a"] = 1
    some_dict["c"] = 3
    list(some_dict.keys())
    Result:
    ['b', 'a', 'c']Pass Icon
  • To check for whether a value exists in a dictionary, we can use some_value in some_dict.values().

  • >
    some_dict = {
    "a": 1,
    "b": 2,
    }
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    1 in some_dict.values()
    Result:
    TruePass Icon
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    3 in some_dict.values()
    Result:
    FalsePass Icon
  • Two dicts are equal if they have exactly the same keys and values.

  • >
    dict_1 = {
    "a": 1,
    "b": 2,
    }

    dict_2 = {
    "a": 1,
    "b": 2,
    }

    dict_1 == dict_2
    Result:
    TruePass Icon
  • >
    dict_1 = {
    "a": 1,
    "b": 2,
    }

    dict_2 = {
    "a": 10,
    "b": 2,
    }

    dict_1 == dict_2
    Result:
    FalsePass Icon
  • Note that we have to quote string keys in Python. Some languages, most notably JavaScript, allow unquoted key names in data structures similar to dictionaries. For example, the JavaScript object {name: 'Amir'} has one property, whose key is the string 'name'.

  • In Python, {name: 'Amir'} is an object whose key comes from the variable name, not the string "name"! If name isn't defined, that's an error.

  • >
    seating_chart = {
    name: "A32",
    }
    Result:
    NameError: name 'name' is not definedPass Icon
  • >
    name = "Amir"
    seating_chart = {
    name: "A32",
    }
    seating_chart["Amir"]
    Result:
    'A32'Pass Icon
  • As we've seen, dictionary item access happens via the indexing operator, like some_dict[some_key]. We can't use attribute access syntax, like some_dict.some_key. If we try that, it's an AttributeError.

  • >
    cat_names = {
    "Amir": "Ms. Fluff",
    "Betty": "Keanu",
    }
    cat_names.Amir
    Result:
    AttributeError: 'dict' object has no attribute 'Amir'Pass Icon
  • Python's dictionary keys can be many types: tuples, strings, integers, etc. However, there are some limitations. We can't use lists or other dictionaries as keys. Trying to use either of those types as keys raises a TypeError.

  • >
    treasure_locations = {
    [4, 5]: "bronze",
    [12, 7]: "silver",
    [8, 23]: "gold",
    }
    treasure_locations[[12, 7]]
    Result:
    TypeError: unhashable type: 'list'Pass Icon
  • Future lessons will explore the reason behind this in detail.

  • Here's a code problem:

    Write a dictionary, en_fr_dict, that maps english words to their french equivalents. Fortunately, we only need translations for "one", "two", and "three".

    • "one" should translate to "un".
    • "two" should translate to "deux".
    • "three" should translate to "trois".

    Since we want to translate from English to French, the keys should be the English words and the values should be the French words.

    en_fr_dict = {
    "one": "un",
    "two": "deux",
    "three": "trois",
    }
    (en_fr_dict["one"], en_fr_dict["two"], en_fr_dict["three"])
    Goal:
    ("un", "deux", "trois")
    Yours:
    ("un", "deux", "trois")Pass Icon