Dictionaries¶
Note
Be sure to activate your virtual environment in your command/terminal window before starting the Python REPL.
Dictionary Basics¶
Dictionaries are unordered key-value pairs, similar to hash maps or associative arrays in other languages.
>>> clothing = {'shoes': 2, 'shirts': 3}
>>> clothing
{'shirts': 3, 'shoes': 2}
We can see that the type of this new object is dict (short for dictionary):
>>> type(clothing)
<class 'dict'>
Note that the keys can be any immutable type. So we could also use numbers or tuples as the dictionary key.
We can retrieve particular values based on their key:
>>> clothing['shoes']
2
We can also add or update key-value pairs:
>>> clothing['socks'] = 6
>>> clothing
{'socks': 6, 'shirts': 3, 'shoes': 2}
>>> clothing['socks'] = 8
>>> clothing
{'socks': 8, 'shirts': 3, 'shoes': 2}
We can remove key-value pairs too:
>>> del clothing['shoes']
>>> clothing
{'socks': 8, 'shirts': 3}
What happens if we try to access a key that doesn’t exist?
>>> clothing['shoes']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'shoes'
If we loop over a dictionary, it will only loop over the keys:
>>> for item in clothing:
... print(item)
...
socks
shirts
If we want to loop over key-value pairs, we can use the items method:
>>> for article, count in clothing.items():
... print("I have {} {}".format(count, article))
...
I have 8 socks
I have 3 shirts
Dictionary Behavior¶
When you check a dictionary for containment, it will check the keys, but not the values:
>>> ages = {4: 2, 3: 1}
>>> 4 in ages
True
>>> 1 in ages
False
Dictionaries are truthy if they contain any key-value pairs and falsey if they are empty:
>>> things = {}
>>> if not things:
... print("There are no things")
...
There are no things
>>> things['hat'] = 2
>>> things
{'hat': 2}
>>> if not things:
... print("There are no things")
...
The list, int, and str, functions we already learned about are actually constructors:
>>> list()
[]
>>> int()
0
>>> str()
''
Dictionaries also have a constructor called dict.
>>> dict()
{}
>>> help(dict)
Dictionaries can be created from lists of two-item tuples (or lists of any two-item iterables):
>>> letters = [('a', 0), ('b', 1)]
>>> letter_dict = dict(letters)
>>> letter_dict
{'a': 0, 'b': 1}
The reverse of this is the items method, that extracts the key-value pair items of the dictionary:
>>> letter_dict.items()
dict_items([('a', 0), ('b', 1)])
Notice that a list isn’t returned from this:
>>> letter_items = letter_dict.items()
>>> type(letter_items)
<class 'dict_items'>
For performance reasons, Python 3 often returns collections that are not regular lists. You can iterate over these collections as usual and in general they act just like lists.
If you need an actual list, you can always pass an iterable into a list constructor:
>>> list(letter_items)
[('a', 0), ('b', 1)]
Dictionary Exercises¶
Translate¶
Make a program translate.py, that will take a list of words in one language and transliterate each word into another language.
Here is an (over-simplified) example translation dictionary for translating from Spanish to English:
>>> words = {'esta': 'is', 'la': 'the', 'en': 'in', 'gato': 'cat', 'casa': 'house', 'el': 'the'}
An example of how this program should work:
$ python translate.py el gato esta en la casa
the cat is in the house
Count Words¶
- Create a string containing the
Declaration of Independence - Create a dictionary recording the number of times all two letter words occur in the Declaration of Independence. The keys should be words and the values should be the count.
As a bonus exercise, remove words that are not alphanumeric.
Anagrams¶
Make a program anagrams.py that takes two words and prints out whether or not the two words are anagrams.
$ python anagrams.py tea eat
anagrams :)
$ python anagrams.py tea treat
not anagrams :(
$ python anagrams.py sink skin
anagrams :)
$ python anagrams.py sinks skin
not anagrams :(
Encode¶
Make a program encode.py that takes a word and prints out the numeric representation of each letter in the word, starting with A at 1.
Example usage:
$ encode.py z
26
$ encode.py abc
1 2 3
$ encode.py Trey
20 18 5 25
Decode¶
Make a program decode.py that takes any number of integers as arguments and prints the word that the integers represent (1 is the letter A, 2 is B, 3 is C, etc.).
Example usage:
$ encode.py 26
Z
$ encode.py 1 2 3
ABC
$ encode.py 20 18 5 25
TREY