dict

Table of Contents

dict reference

dict()
dict(mapping)
dict(iterable)
dict(**kwargs)

len(d)
d[key]
d[key] = value
del d[key]
key in d
key not in d
iter(d)

D.items()  D.iteritems()  D.viewitems()
D.keys()   D.iterkeys()   D.viewkeys()
D.values() D.itervalues() D.viewvalues()

D.clear()
D.copy()               a shallow copy of D
D.fromkeys(S[,v])      new dict with keys from S and values equal to v(None).
D.get(k[,d])           D[k] if k in D, else d(None)
D.has_key(k)           True if D has a key k, else False
D.pop(k[,d]) -> v      remove specified key and return the corresponding value.
                       d(KeyError) if key is not found
D.popitem() -> (k, v)  remove and return a (key, value) KeyError if empty
D.setdefault(k[,d])    D.get(k,d), also set D[k]=d if k not in D
D.update([E, ]**F)
    If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
    If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
    In either case, this is followed by: for k in F: D[k] = F[k]

items, iteritems, viewitems discussion

Py2

>>> d = {'a': 0}
>>> it = d.iteritems()
>>> d['b'] = 1
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
>>> view = d.viewitems()
>>> d['c'] = 2
>>> it = iter(view)
>>> next(it)
('a', 0)
>>> d['d'] = 3
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration

Py3

Convert a list to a dictionary howto

dict(izip(*([iter(a)]*2)))
iter(h)    #create an iterator from the array, no copies here
[]*2       #creates an array with two copies of the same iterator, the trick
izip(*())  #consumes the two iterators creating a tuple
dict()     #puts the tuples into key,value of the dictionary