View Category

Define an empty map

python
map = {}

Define an unmodifiable empty map

python
import collections
EmptyDict = collections.namedtuple("EmptyDict", "")
e = EmptyDict()

Define an initial map

Define the map {circle:1, triangle:3, square:4}
python
shapes = {'circle': 1, 'square': 4, 'triangle': 2}
shapes = dict(circle=1, square=4, triangle=2)

Check if a key exists in a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
python
pets = dict(joe='cat', mary='turtle', bill='canary')
if ("mary" in pets) print "ok"

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
python
print pets['joe']

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog"
python
pets['rob'] = 'dog'

Remove an entry from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
python
print pets.pop('bill')

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
python
from collections import defaultdict
h = defaultdict(int)
for k in "abacbb":
h[k] += 1

h = {}
for k in "abacbb":
h[k] = h.setdefault(k, 0) + 1
from collections import Counter
h = Counter("abacbb")
print(h)

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
python
c = defaultdict(list)
for k in ["one", "two", "four", "three", "five"]:
c[len(k)].append(k)
from itertools import groupby
lst = ["one", "two", "four", "three", "five"]
c = dict((k, list(g)) for k,g in
groupby(sorted(lst, key=lambda x: len(x)), key=lambda x: len(x)))
print(c)