Computer Science 15-112, Spring 2012
Class Notes: Dictionaries (Maps)
d = dict() d["fred"] = "555-1212" d["wilma"] = "555-3456" print d["fred"] # now fred and wilma get married, so... d["fred"] = d["wilma"] print d["fred"]
# values may be mutable
d = dict()
a = [1,2]
d["fred"] = a
print d["fred"]
a += [3]
print d["fred"] # sees change in a!
# but keys may not be mutable
d[a] = 42 # TypeError: unhashable type: 'list'
# Create an empty dictionary d = dict() print d # prints {} # Create an empty dictionary using braces syntax d = { } print d # prints {} # Create a dictionary from a list of (key, value) pairs pairs = [("cow", 5), ("dog", 98), ("cat", 1)] d = dict(pairs) print d # prints {'dog': 98, 'cow': 5, 'cat': 1} # Create a dictionary from a list of (key, value) pairs with braces syntax d = { "cow":5, "dog":98, "cat":1 } print d # prints {'dog': 98, 'cow': 5, 'cat': 1}
Operation | Result |
---|---|
len(d) | Return the number of items (key-value pairs) in the dictionary d. |
d.clear() | Remove all items from the dictionary d. |
d.copy() | Return a shallow copy of the dictionary d. |
d.popitem() | Remove and return an arbitrary (key, value) pair from the dictionary. If the dictionary is empty, calling popitem() raises a KeyError. |
for key in d | Iterate over
all keys in d. For example: d = { "cow":5, "dog":98, "cat":1 } for key in d: print key, d[key] |
Operation | Result |
---|---|
key in d | Return True if d has a key key, else False. |
key not in d | Equivalent to not key in d. |
d[key] | Return the item of d with key key. Raises a KeyError if key is not in the map. |
get(key[, default]) | Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError. |
d[key] = value | Set d[key] to value. |
del d[key] | Remove d[key] from d. Raises a KeyError if key is not in the map. |
Operation | Result |
---|---|
update([other]) | Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None. |
def mostFrequent(a): maxValue = None maxCount = 0 counts = dict() for element in a: count = counts[element] if (element in counts) else 0 count += 1 counts[element] = count if (count > maxCount): maxCount = count maxValue = element return maxValue print mostFrequent([2,5,3,4,6,4,2,4,5]) # prints 4 # once again, using get() with default value def mostFrequent(a): maxValue = None maxCount = 0 counts = dict() for element in a: count = 1 + counts.get(element, 0) counts[element] = count if (count > maxCount): maxCount = count maxValue = element return maxValue print mostFrequent([2,5,3,4,6,4,2,4,5]) # prints 4
carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem