Dictionaries: basic-level questions

If you need help reviewing Dictionaries, take a look at these resources:

Each question has a "Toggle Solution" button -- click it to reveal that question's solution.

Conceptual Questions

Question 1

What type of objects can be used as keys for dictionaries? What type of objects can be used as values?

Any immutable object can be used as a key — this includes numbers, strings, and tuples. Mutable objects, such as lists and dictionaries, are not allowed to be used as keys. Anything can be used as a value, however.

Question 2

How many objects can a single key map to?

A single key can only map on to one value. That value can, however, be a sequence like a tuple or a list, so you can effectively map to multiple things (but it still only counts as one value).

Question 3

Are dictionaries ordered?

Python dictionaries are not ordered. If you were to iterate through the dictionary, the order in which you iterate through them is not necessarily the order in which you added them.

What would Python print?

Question 4

>>> logins = {'albert': 'cs61a-tg'}"
>>> logins['albert']
______
>>> logins['cs61a-tg']
______
>>> logins['allen'] = None
>>> len(logins)
______
>>> for elem in logins:
...     print(elem)
______
>>> for key, value in logins.items():
...     print(key, value)
______