© Springer-Verlag London 2014
Kent D. LeePython Programming FundamentalsUndergraduate Topics in Computer Sciencehttps://doi.org/10.1007/978-1-4471-6642-9_12

12. Appendix E: Dictionary Operators and Methods

Kent D. Lee 
(1)
Luther College, Decorah, IA, USA
 
 
Kent D. Lee
This documentation was generated from the Python documentation available by typing help(dict) in the Python shell. In the documentation found here the variable D is a reference to a dictionary. A few methods were omitted here for brevity (Table 12.1).
Table 12.1
Dictionary operators and methods
Method
Returns
Comments
dict()
dict
New empty dictionary
dict(mapping)
dict
New dictionary initialized from a mapping object’s (key, value) pairs
dict(seq)
dict
New dictionary initialized as if via
   
D $$=$$ {}
   
for k, v in seq
   
D[k] $$=$$ v
dict(**kwargs)
dict
New dictionary initialized with the name $$=$$ value pairs in the keyword arg list. For example: dict(one $$=$$ 1, two $$=$$ 2)
k in D
bool
True if D has key k, else False
del D[k]
 
Deletes key k from dictionary D
D1$$==$$ 2
bool
Returns True if dictionaries D1 and D2 have same keys mapped to same values
D[k]
value type
Returns value k maps to in D. If k is not mapped, it raises a KeyError exception
iter(D)
iterator
Returns an iterator over D
len(D)
int
Returns the number of keys in D
D1!$$=$$D2
bool
Returns True if D1 and D2 have any different keys or keys map to different values
repr(D)
str
Returns a string representation of D
D[k]$$=$$e
Stores the key,value pair k,e in D
D.clear()
None
Remove all items from D
D.copy()
dict
A shallow copy of D
D.get(k[,e])
value type
D[k] if k in D, else e. e defaults to None
D.items()
items
A set-like object providing a view on D’s items
D.keys()
keys
A set-like object providing a view on D’s keys
D.pop(k[,e])
v
Remove specified key and return the corresponding value. If key is not found, e is returned if given, otherwise KeyError is raised
D.popitem()
(k, v)
Remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty
D.setdefault(k[,e])
D.get(k,e)
Returns D.get(k,e) and also sets d[k] $$=$$ e if k not in D
D.update(E, **F)
None
Update D from dict/iterable E and F
   
If E has a .keys() method, does: for k in E: D[k] $$=$$ E[k]
   
If E 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]
D.values()
values
An object providing a view on D’s values