Smalltalk collections for Python coders

One of the great things about Python is the way you can easily juggle items around in collections — lists, dictionaries, sets — and the shortcuts you get when you combine them. For example, to get a unique collection of elements in a list: list(set(my_list)) will do it.

Similar things happen in Smalltalk but these nuggets of information are scattered around the net. So I thought I’d write up a translation crib sheet for us all.

Dictionaries

Python Smalltalk
d = {'a':1,'b':2} d := {'a'->1.'b'->2} asDictionary
d['c'] = 3 d at: 'c' put: 3
d.get('d', 'foo') d at: 'd' ifAbsent: 'foo'
d.keys() d keys
d.values() d values
for k, v in d.iteritems(): print k + ':' + v d keysAndValuesDo: [ :k :v | Transcript show: k,':',v,String cr ]
or also: d associations do: [ :kv | Transcript show: kv key,':',kv value,String cr ]

Dictionary things you can’t do in Python

Python Smalltalk
get via values d keyAtValue: 2
get key/value as an Association, a bit like ('c', d['c']) d associationAt: 'c'
create a dictionary straight from a list, taken in pairs d := Dictionary newFromPairs: {'a'. 1. 'b'. 2}

Sets

Python Smalltalk
s = {1, 2, 3} s := {1 . 2 . 3} asSet
s.add(4) s add: 4
s.union([5, 6]) s addAll: {5 . 6} or s,{5 . 6}
len(s) s size
s.intersection(s2) s intersection: s2
s.difference({1, 2}) s difference: {1 . 2}

Lists

Python Smalltalk
l = [1, 1, 2, 3] l := {1. 1. 2. 3} asOrderedCollection
list(set(l)) l asSet asOrderedCollection
len(l) l size
sorted(l) l sort
[ 2*x for x in l ] l collect: [ :x | 2*x ]
[ a*b for a, b in zip(l1, l2) ] l1 with: l2 collect: [ :a :b | a*b ]
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s