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
Mapis an even closer equivalent.>
user = {"name": "Amir","email": "amir@example.com",}user["name"]Result:
'Amir'
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 raisesIndexError.>
user = {"name": "Amir","email": "amir@example.com",}user["age"]Result:
KeyError: 'age'
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"] = 36userResult:
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"]userResult:
{'name': 'Amir'}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"]userResult:
KeyError: 'age'
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'
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
1vs."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']
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
some_dictResult:
{'1': 'a', 1: 'b'} We've used
value in some_listto decide whether a list contains a value. That also works with dictionaries:some_key in some_dictdecides whether the dictionary contains that key.>
some_dict = {"a": 1,}"a" in some_dictResult:
True
>
some_dict = {"a": 1,}"b" in some_dictResult:
False
The
not inoperator also works with dicts.>
some_dict = {"a": 1,}"b" not in some_dictResult:
True
Although we can use
into check for keys, we can't use it to check for values. Theinoperator only searches keys.>
some_dict = {"a": 1,}1 in some_dictResult:
False
We can get a dictionary's keys with the
.keys()method.>
some_dict = {"a": 1,"b": 2,}list(some_dict.keys())Result:
['a', 'b']
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']
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]
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"] = 2some_dict["a"] = 1some_dict["c"] = 3list(some_dict.keys())Result:
['b', 'a', 'c']
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:
True
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
3 in some_dict.values()Result:
False
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_2Result:
True
>
dict_1 = {"a": 1,"b": 2,}dict_2 = {"a": 10,"b": 2,}dict_1 == dict_2Result:
False
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 variablename, not the string"name"! Ifnameisn't defined, that's an error.>
seating_chart = {name: "A32",}Result:
NameError: name 'name' is not defined
>
name = "Amir"seating_chart = {name: "A32",}seating_chart["Amir"]Result:
'A32'
As we've seen, dictionary item access happens via the indexing operator, like
some_dict[some_key]. We can't use attribute access syntax, likesome_dict.some_key. If we try that, it's anAttributeError.>
cat_names = {"Amir": "Ms. Fluff","Betty": "Keanu",}cat_names.AmirResult:
AttributeError: 'dict' object has no attribute 'Amir'
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'
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")