This week's lecture covers reading mouse input as well as list methods and dictionaries. Last week's blog post discussed the list data type and several common list methods. This blog post will explain the dictionary data type as well as various dictionary methods.
This week's mini project is writing the merge
function for the game 2048. In next week's mini project we will build the rest of the game.
key: value
pairs, with each key in a dictionary being distinct. Unlike sequences (i.e., lists), which are indexed by a range of numbers, dictionaries are indexed by keys, which can generally be any immutable type (e.g., strings, numbers, certain tuples). Thus, it's useful to use a dictionary over another data structure, such as a list, when you need to associate values with keys so you can efficiently look them up later. A pair of braces creates an empty dictionary: {}
. Below are some common dictionary methods:
a_dict[key]
or a_dict.get(key)
. Note that if the key is not in the dictionary, a_dict[key]
raises a KeyError
error, whereas a_dict.get(key)
returns None
.a_dict[key] = value
. This mutates the dictionary a_dict
so that the given key now maps to the given value.a_dict.has_key()
or key in a_dict
. The former returns a Boolean expression based on whether the given key is a key in the dictionary a_dict
.a_dict.items()
. This returns a list of (key, value)
pairs for all the keys in dictionary a_dict
. This is useful for looping over all the key/value pairs in a dictionary.a_dict.keys()
. This returns a list of the keys in dictionary a_dict
.a_dict.values()
. This returns a list of the values in dictionary a_dict
.Mini Project 6
See my complete implementation of Mini Project 5 on GitHub.