keep track of the number of times a two is rolled… a three… up through six
use multiple assignment for initializing your counts!
Dice Rolls Solution
Dice Rolls
Whew!
That was a long if-else. What if we had to write one for two twenty-sided dice?
that would be pretty lengthy
and consequently error prone
If there were only a way to dynamically create names and associate values to them.
We'll get to that in a second. First: compound types, mapping types and dictionaries…
Revisiting Compound Types
Compound types: values that are made up of other values.
Sequence types are compound types. We know three sequence types. What are they?
string
list
tuple
Mapping Types
Another kind of compound type is a mapping type.
A mapping type is a data type that is made of a collection of keys (think of names) and their associated values. The only mapping type in Python is a dictionary.
Dictionaries
A dictionary is an unordered collection of key/value pairs.
key is an item that is used to look up values in a dictionary; think of keys as names or labels.
keys must be immutable objects (they're usually strings or ints)
the values that are associated with keys can be any type!
in other languages dictionaries are called associative arrays or hash tables
Dictionaries Syntax
Let's take a look at some examples
dictionaries are delimited by curly braces - { and }
an empty dictionary is {}
each key value pair in a dictionary is separated by a comma
keys and values are linked together by a colon, the key before and the value after
What are the keys and what type are they? What are the values and what type are they?
d1
keys - the strings "first_name" and "fav_food"
values - the strings "joe" and "cleo's"
d2
keys - the ints 28 and 6 …and the string "entirely different"
values - the strings "foo" and "bar" … and the list ["baz"]
Retrieving Values at Keys
You can use the key like a list index to retrieve a value at that key. What does this code print out?
Keys That Don't Exist!
Let's try that again… but with a key that doesn't exist. What do you think will happen here?
Retrieval Using the get Method
You can also retrieve a value from a dictionary by calling the get method. get takes two arguments:
the key of the element you want to retrieve
an optional default value in case that key doesn't exist yet
What do you think this code outputs?
Key/Value Pairs
So… things are a bit different when adding keys and values to a dictionary. There is no error if you use a key that doesn't exist in order to assign a value to it (that is… to create a new key/value pair).
Key/Value Pairs Continued
If the key already exists… and you use the assignment operator, you are just associating a new value with an existing key.
What does this code output?
Dictionaries and Mutability
Based on what we've seen so far… are dictionaries mutable or immutable?
Dictionaries are mutable!
We Can Iterate Over Dictionaries
Let's run this code. What would you expect this to print? Does it match what actually happens?
Dictionary Views
Another way to iterate over a dictionary is to convert it to a special sequence called a dictionary view.
the items() method returns a dictionary view (another iterable object)
each element in the view is a tuple
the first element in each tuple the key, and the second, the value
What type is the type of variable, i? How many iterations are there? What is the value of i at each iteration?
Converting a Dictionary to a Bunch of Tuples
A few notes….
items is a list like value that contains tuples
in the for loop, t is always a tuple
2 iterations, with t being a tuple that represents a name value pair
Iterating over a Dictionary Using items()
Now… we have a tuple… how do we print out each key and value individually (how do we unpack again?)
Dictionaries Are Unordered
Unlike sequence types like string, list or tuple, dictionaries are unordered. That means that the order of the key value pairs cannot be guaranteed! Let's take a look. Intuitively, what's the first thing that we think will be printed out?
in and len()
The in and not in operators work with dictionary keys; len() gives back the number of key/value pairs →
Summary Questions
how do we construct a dictionary literal?
how do we create an empty dictionary?
are dictionaries mutable or immutable?
are dictionaries ordered or unordered
how do we access a value at a key… what happens if they key doesn't exist?
what's the exception to the above?
what's another way of accessing a value?
More Dictionary Methods
By the way, here are a few more dictionary methods:
values() - get all values as a list-like structure
keys() - get all keys as a list-like structure (
pop(k, [d]) - removes element at key, k, and returns it (returns d if k doesn't exist)
popitem() - removes and returns some name/value pair as tuple
update(dictionary) - overwrites all values at keys in original with values at keys from dictionary passed in
values, keys
values and keys give back dictionary views (they essentially act like lists) of either all values or all keys of the dictionary that they're called on. What does this output? →
Note that the order of the keys and values cannot be guaranteed!
pop
pop removes and returns the item at the key specified. What does this output?→
popitem
popitem removes and returns an arbitrary key/value pair. What does this output?→
Note that the key/value pair removed and returned will not always be the same!
update
update adds key/value pairs (or updates values if keys already exist) from another dictionary to the dictionary that update is called on. What does this output?→
Changing a Value Based on the Existing Value
To change a value base on an existing value, such as incrementing a number, you can simply do something like this (adds one to the current value at fga):
Changing a Value Based on the Existing Value
But what if it doesn't exist yet? What happens here? →
Summary Answers
dictionaries are delimited by curly braces, key value pairs are separated by commas, with each key and value joined by a colon
{}
they're mutable
order cannot be guaranteed
d["some key"], exception
assignment
get method
Back to Dice!
Try reimplementing our dice program so that it uses a dictionary to store the frequency of rolls (each roll as a key, each value as a count). (hint: use in, the get method or a try-except to deal with keys that don't exist).