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

Sum00 Final Exam Review: Transposing a Dictionary

Okay, I'm assuming that I am given a dictionary called currentDict and the transposition of the dictionary will be transDict

currentDict keysDo: [:i | transDict add: (key: (currentDict at: i) value: i)]

Just curious, Mark. I spent some time doing lookups for this to get it down to one line of code and just the two data structures. If something like this on the test, do we need just one line to get full credit or maybe do we get bonus points for getting it down to one line? I couldn't imagine being able to do this for some other random function in just one line with no reference to help me.

Adam Blaiss

I usually don't expect the impossible :-). BTW, the above code doesn't work. Mark Guzdial

D'oh! I forgot the key:value: was a class method from Association. Okay, this should do the trick:

currentDict keysDo: [:i | transDict add: (Association key: (currentDict at: i) value: i)]

Adam Blaiss

Another approach to this would be something like:

currentDict valuesDo: [:i| transDict at: i ifAbsentPut: [(currentDict keyAtValue: i)]].

different, yet equally exciting. Of course, if you could find a way to have a small bear of some variety come out and move the dictionary parts around for you on the screen, all with one line of code, that would be even more exciting.
Shaggz Mickley

Or maybe have South Park faces stored in the Dictionary slots! :-) Mark Guzdial

How about this?
currentDict keysDo: [:i| transDict at: (currentDict at: i) put: i].

Chau Vo

Chau i think your version doesn't get rid of the old associations...
When you loop each time don't you not only want to add the new association but get rid of the old one (i.e. the keyvalue pair bear/2,
in your iteration create the new keyvalue pair 2/bear and get rid of the old keyvalue pair bear/2)?

Actually, I think you would get rid of old associations if you were working w/ just one dictionary... everyone above has been working with 2, so his code works... I did it with one dictionary, thereby transposing it and deleting the old associations as follows:

d keysDo: [:key | d at: (d at: key) put: key. d removeKey: key.].

Shaun Dishman

Yeah that's what I was thinking... using removeKey..

Link to this Page