Comparisons
Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.
Your colleague is thinking about an alternate way of representing dictionaries whose keys are all nonnegative integers and have at least 1 key. She suggests a process that:
- Find the largest key in the given dictionary
d
; call itmax_key
. - Make a list of length
max_key + 1
, containing allNone
s. (For example, ifmax_key
is 2, make the list[None, None, None]
.) - For each key
k
in the dictionaryd
, set the list element at indexk
to bed[k]
. - Print the list.
For example, when given the dictionary
d = {3: 'orange', 1: 'apple', 4: 'banana'}
,
she suggests we store this as the list
[None, 'apple', None, 'orange', 'banana']
.
What would her representation be when given the dictionary {2: [1, 2, 3], 0: 'broccoli'}
?
['broccoli', None, [1, 2, 3]]
.Please code up a program to implement your colleague's plan. The first line of your code should define the input dictionary d
and the program should print out the resulting list.
Your colleague claims that, if she knows what list the program printed, then she can always reconstruct exactly what dictionary was given to the program.
Is her claim correct?
Hint: If her claim is correct, then there are no dictionaries other than {3: 'orange', 1: 'apple', 4: 'banana'}
which would also print [None, 'apple', None, 'orange', 'banana']
. Recall that dictionary values can be anything...
{3: 'orange', 1: 'apple', 4: 'banana', 0: None}
,
{3: 'orange', 1: 'apple', 4: 'banana', 2: None}
, and
{3: 'orange', 1: 'apple', 4: 'banana', 0: None, 2: None}
would also print [None, 'apple', None, 'orange', 'banana']
. So, she cannot know exactly what dictionary was given, based on the list printout.
The problem, in short, is that it is ambiguous whether an entry of None
in the list indicates that the key did not exist, or whether it did exist and simply had the associated value of None
."""
Note, that is not to say that dictionaries are always superior to lists! Use dictionaries when you want a mapping of keys to values; use lists when you want an ordered collection of values.
Next Exercise: Survey