Operation | Result | Example |
len(d) | the number of items (key-value pairs) in dictionary d |
d = { 1:[1,2,3,4,5], 2:"abcd" }
print(len(d))
|
d.copy() | new dictionary with a shallow copy of d |
d1 = { 1:"a" }
d2 = d1.copy()
d1[2] = "b"
print(d1)
print(d2)
|
d.clear() | remove all items from dictionary d |
d = { 1:"a", 2:"b" }
d.clear()
print(d, len(d))
|
for key in d | Iterate over all keys in d. |
d = { 1:"a", 2:"b" }
for key in d:
print(key, d[key])
|
Operation | Result | Example |
key in d | test if d has the given key |
d = { 1:"a", 2:"b" }
print(0 in d)
print(1 in d)
print("a" in d) # surprised?
|
key not in d | test if d does not have the given key |
d = { 1:"a", 2:"b" }
print(0 not in d)
print(1 not in d)
print("a" not in d)
|
d[key] | the item of d with the given key. Raises a KeyError if key is not in the map. |
d = { 1:"a", 2:"b" }
print(d[1])
print(d[3]) # crash!
|
d[key] = value | set d[key] to value. |
d = { 1:"a", 2:"b" }
print(d[1])
d[1] = 42
print(d[1])
|
get(key[,default]) | the value for key if key is in the dictionary, else default (or None if no default is provided). |
d = { 1:"a", 2:"b" }
print(d.get(1)) # works like d[1] here
print(d.get(1, 42)) # default is ignored
print(d.get(0)) # doesn't crash!
print(d.get(0, 42)) # default is used
|
del d[key] | remove d[key] from d. Raises KeyError if key not in d. |
d = { 1:"a", 2:"b" }
print(1 in d)
del d[1]
print(1 in d)
del d[1] # crash!
|
Operation | Result | Example |
d1.update(d2) | update the dictionary with the key/value pairs from other, overwriting existing keys. |
d1 = { 1:"a", 2:"b" }
d2 = { 2:"c", 3:"d" }
d1.update(d2)
d2[4] = "e"
print(d1)
print(d2)
|