kota's memex

Python's version of a hash map. Like the rest of the language, there's no type checking.

alien = {'color': 'green', 'points': 5}
print(alien['color'])
print(alien['points'])

Dictionaries are resizable in python by just writing to a new key:

alien['x'] = 0
alien['y'] = 25

removing a key

Much list with lists, the del builtin is used:

del alien['points']

accessing values

If the key does not exist in a normal value access statement you get a runtime error! As a result, you should normally use get to access keys.

points = alien.get('points', 'No point value assigned')

Without the "default value" python will return a type None which indicates that no value existed.

setdefault()

You can set a default value for a dictionary:

numberOfPets = {'dogs': 2}
numberOfPets.setdefault('cats', 0) # Does nothing if 'cats' exists.
numberOfPets['cats'] += 10
print(numberOfPets['cats']) # 10

looping

You need to use the items() or keys() methods when looping:

user = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
}

for key, value in user.items():
    print(key)
    print(value)

for key in user.keys():
    print(user[key])