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.
Larry is thinking about an alternate way of representing dictionaries whose keys are all nonnegative integers and have at least 1 key. He suggests a function convert_dictionary
that:
- Finds the largest key in the given dictionary
d
; call itmax_key
. - Makes 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
, sets the list element at indexk
to bed[k]
. - Returns the list.
For example:
result = convert_dictionary({3: 'orange', 1: 'apple', 4: 'banana'})
print(result)
would print the result list
[None, 'apple', None, 'orange', 'banana']
.
What would convert_dictionary({2: [1, 2, 3], 0: 'broccoli'})
return?
['broccoli', None, [1, 2, 3]]
.Please write a program to implement Larry's plan according to the description above.
Larry claims that, if we know what list the program returned, then we can always reconstruct exactly what dictionary was given to the program.
Is his claim correct?
Hint: If his 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, he 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: Make it Concise