View this PageEdit this PageAttachments to this PageHistory of this PageHomeRecent ChangesSearch the SwikiHelp Guide
Hotspots: Admin Pages | Turn-in Site |
Current Links: Cases Final Project Summer 2007

Sp00 Final Exam Review: Transposing a Dictionary

See Final Exam Review - Sp2000

Here's one line transposing a dictionary, with one line above it making sure the new dictionary is empty:

newDictionary := nil. "Make sure you start with an empty dictionary"

({ 'Fred'->'Wilma'. 'Barny'->'Betty'. 'George'->'Martha'. 'Ozzie'->'Harriet' } as: Dictionary) associationsDo: [:assoc | (newDictionary ifNil: [ newDictionary := Dictionary new] ifNotNil: [newDictionary]) at: assoc value put: assoc key ].

What is this problem supposed to show? ...that we can recall some obscure squeak method that was poorly documented? ...that we can write obfuscated Squeak code?

Jared Ivey
That you know what a Dictionary is? That you know that it's made up of associations? That you know how to create and manipulate Dictionaries? :-) Mark Guzdial

Is there going to be something this specific on the final? I had no clue what to do when I first read this. We only used a Dictionary once in our program, so I was not really familiar with them.

Susi Rathmann

I am not sure if this works, but is it in the ball park?

transDict = is your dictionary

keysDo:[:word| transDict add:(Association key:(transDict at: word) value: word). removeKey: word. ].


How about a very simple oneliner?

dict keysAndValuesDo: [:b :c | dict add: c->b. dict removeKey: b. ].

who can beat me?

Nolan Leake

I read the problem "create the transpose of the dictionary" to mean "make a new dictionary, and don't alter the original" but I could be wrong about that.

Also, consider the dictionary:
{ 'a'->'a'. 'b'->'b'. 'c'->'c' }

both of the above will end up with an empty dictionary. The key removal should come before adding the new association.

Jared Ivey

I tested my code, except for the part about destroying the orginal dictionary which can easily be fixed by the following code, it seems to work for me.

dict _ Dictionary new.
newDict _ Dictionary new.
dict add: (Association key: 'Fred' value: 'Wilma').
dict add: (Association key: 'Barney' value: 'Betty').
dict add: (Association key: 'George' value: 'Martha').
dict add: (Association key: 'Ozzie' value: 'Harriet').

dict keysDo: [:word| newDict add: (Association key: (dict at: word) value: word ).].


Link to this Page