The Python dictionary data structure is often very useful. See https://docs.python.org/2/tutorial/datastructures.html#dictionaries
In [ ]:
%pylab inline
Example of mapping color names to RGB tuples and/or hex strings.
See http://faculty.washington.edu/rjl/classes/am583s2014/notes/memory.html
In [ ]:
d = {'red':[1,0,0], 'blue':'#0000ff'}
print d['red']
In [ ]:
fill([0,3,3,0,0],[0,0,3,3,0],color=d['red'])
fill([1,2,2,1,1],[1,1,2,2,1],color=d['blue'])
Can add new items to a dictionary, or change the value for an existing key:
In [ ]:
d['blue'] = [0,0,1]
d['husky purple'] = [ 0.22352941, 0.15294118, 0.35686275]
d['husky gold'] = '#f0d576'
print d
In [ ]:
fill([0,3,3,0,0],[0,0,3,3,0],color=d['husky gold'])
fill([1,2,2,1,1],[1,1,2,2,1],color=d['husky purple'])
Can use a dictionary to get something like an array with indexing starting at 1, or for a sparse array:
In [ ]:
d = {} # initialize with empty dictionary
for j in range(5):
d[j+1] = j+1
print d
print d[2] # should be 2
In [ ]:
d[2000] = 'two thousand'
print d
print d.keys() # list all the keys
You can iterate over items in a dictionary, but they might come up in random order:
In [ ]:
for key,value in d.iteritems():
print "key ",key," gives value ",value
One useful dictionary is os.environ, which contains any environment variables you have set:
In [ ]:
import os
HOME = os.environ['HOME']
print HOME
Dictionary keys can be any immutable objects, such as an int, float, string, or tuple:
In [ ]:
d = {}
d[(1,2)] = 3
print d
a = (1,2)
print d[a]
d[a] = 4 # changes the value associated with key (1,2)
print d
But not a mutable object like a list:
In [ ]:
d[[3,4]] = 5
In [ ]: