Creating Dictionaries


In [89]:
# This is some IPython %magic
%xmode plain


Exception reporting mode: Plain

In [90]:
# with initial values
c = {'foo': 'bar', 'baz': 'qux'}
d = dict([('foo', 'bar'), ('baz', 'qux')])
print c
print d


{'foo': 'bar', 'baz': 'qux'}
{'foo': 'bar', 'baz': 'qux'}

In [91]:
# keys don't have to be strings
z = {
    3: 'a',
    'lol': {'foo': 'bar'},
    None: False,
}
print z


{None: False, 3: 'a', 'lol': {'foo': 'bar'}}

Modifying Values


In [92]:
d = {'foo': 'bar'}
d['baz'] = 'qux'
print d


{'foo': 'bar', 'baz': 'qux'}

In [93]:
x = {'baz': 'qux'}
d.update(x)
print d


{'foo': 'bar', 'baz': 'qux'}

Getting Data Out


In [94]:
d['foo']


Out[94]:
'bar'

In [95]:
# undefined values
d['nope']


Traceback (most recent call last):

  File "<ipython-input-95-318efa976070>", line 2, in <module>
    d['nope']

KeyError: 'nope'

In [96]:
# case-sensitive
d['FOO']


Traceback (most recent call last):

  File "<ipython-input-96-ed9f4f52e085>", line 2, in <module>
    d['FOO']

KeyError: 'FOO'

In [97]:
d.get('nope', 'aha!') # also callable without a default (implies None)


Out[97]:
'aha!'

In [98]:
print d
d.setdefault('nope', 'aha!')
print d


{'foo': 'bar', 'baz': 'qux'}
{'nope': 'aha!', 'foo': 'bar', 'baz': 'qux'}

In [99]:
z[None]


Out[99]:
False

Inspecting


In [100]:
# notice the key order - there is none!
d.keys()


Out[100]:
['nope', 'foo', 'baz']

In [101]:
d.values()


Out[101]:
['aha!', 'bar', 'qux']

In [102]:
d.items()


Out[102]:
[('nope', 'aha!'), ('foo', 'bar'), ('baz', 'qux')]

In [103]:
print d.has_key('foo')
print d.has_key('zzz')


True
False

Deleting Values


In [104]:
del(d['nope'])
print d


{'foo': 'bar', 'baz': 'qux'}

In [105]:
d.clear()
print d


{}