Comparisons

The questions below are due on Thursday June 24, 2021; 11:00:00 AM.
 
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.

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:

  1. Find the largest key in the given dictionary d; call it max_key.
  2. Make 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, set the list element at index k to be d[k].
  4. 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'].

Try Now:

What would her representation be when given the dictionary {2: [1, 2, 3], 0: 'broccoli'}?

It would print ['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.

  No file selected

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.

Try Now:

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

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

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 your colleage 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: Survey

Back to exercises