Comparisons

The questions below are due on Sunday June 30, 2024; 10:00:00 PM.
 
You are not logged in.

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:

  1. Finds the largest key in the given dictionary d; call it max_key.
  2. Makes a list of length max_key + 1, containing all Nones. (For example, if max_key is 2, make the list [None, None, None].)
  3. For each key k in the dictionary d, sets the list element at index k to be d[k].
  4. 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'].

Try Now:

What would convert_dictionary({2: [1, 2, 3], 0: 'broccoli'}) return?

It would return ['broccoli', None, [1, 2, 3]].

Please write a program to implement Larry's plan according to the description above.

  No file selected

Larry claims that, if we know what list the program returned, then we can always reconstruct exactly what dictionary was given to the program.

Try Now:

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...

The claim is not correct. The dictionaries

{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."""

What might be some reasons to prefer to represent key-value pairs (where all keys are nonnegative integers) in a dictionary rather than in a list of the form Larry presents?

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

Back to exercises