Computer Science 15-110, Fall 2010
Class Notes: One-Dimensional Lists
- What is a dictionary?
- Quick Example
- How to...
- Create a dictionary
- Create an empty dictionary (with { })
- Create a dictionary from a list of tuples (with dict())
- Add a key/value
- Delete a key (with del, pop, and clear)
- Get a value from a key
- Get a value from a missing key
- Check if the key exists (with key in dict)
- Use dict.get(key) and dict.get(key, default)
- Modify a key/value
- Get all keys (with dict.keys())
- Usage
- Can use mixed types for keys and values
- Keys are case-sensitive
- Don't use a dictionary like a list
- Recommended Reading
- Examples Using Dictionaries
- Word Counts (from a list of words)
- Sparse Matrices
- Text Adventure
- Suggested Practice Problems
Dictionaries
- What is a dictionary?
- It is a map from keys to values
- Adding, removing, getting, and setting are all fast (eg, much faster than using a sorted list of tuples)
- Keys are a set: they are unique and unsorted
- Quick Example
# Quick Example using a dictionary
says = { } # creates an empty dictionary
says["dog"] = "woof"
says["cat"] = "meow"
print says["dog"] # woof
print says["cat"] # meow
print ("cow" in says) # False
says["cow"] = "moo"
print ("cow" in says) # True
print says["cow"] # moo
print
says
# {'dog': 'woof', 'cow': 'moo', 'cat': 'meow'}
says["dog"] = "bark"
print says["dog"] # bark
print
says
# {'dog': 'bark', 'cow': 'moo', 'cat': 'meow'}
- How to...
- Create a dictionary
# Create an empty dictionary (with {})
d = { } # or d = dict()
print d
# Create a dictionary from a list of tuples (with dict())
d = dict([("dog", 10), ("ant", 0), ("cat", 3)])
print d
- Add a key/value
# Add a key/value
d = { }
d["dog"] = 5
d["cat"] = 7
print d
- Delete a key (with del, pop, and clear)
d = dict([("dog", 10), ("ant", 0), ("cat", 3), ("cow", 7)])
print
d
# {'ant': 0, 'dog': 10, 'cow': 7, 'cat': 3}
# Delete a key with del dict[key]
del d["dog"]
print d # {'ant': 0, 'cow': 7, 'cat': 3}
# Delete a key with dict.pop(key)
value = d.pop("cat")
print value # 3
print d # {'ant': 0, 'cow': 7}
# Delete all keys with dict.clear()
d.clear()
print d # { }
- Get a value from a key
# Get a value from a key with dict[key]
d = dict([("dog", 10), ("ant", 0), ("cat", 3), ("cow", 7)])
print d["dog"] # 10
- Get a value from a missing key
Problem:
# Try to get a value from a missing key with dict[key]
d = dict([("dog", 10), ("ant", 0), ("cat", 3), ("cow", 7)])
print d["pig"] # KeyError: 'pig' (key not in dictionary!)
Solutions:
# Detect a missing key with (key in dict):
d = dict([("dog", 10), ("ant", 0), ("cat", 3), ("cow", 7)])
if ("pig" in d):
print d["pig"]
else:
print "pig is not in", d
# Get a value from a missing key with dict.get(key)
d = dict([("dog", 10), ("ant", 0), ("cat", 3), ("cow", 7)])
print d.get("dog") # 10
print d.get("pig") # None
# Get a value from a missing key with dict.get(key, default)
d = dict([("dog", 10), ("ant", 0), ("cat", 3), ("cow", 7)])
print d.get("dog", 42) # 10
print d.get("pig", 42) # 42
- Modify a key/value
# Modify a key/value
d = { }
d["dog"] = 5
d["cat"] = 7
print d
d["dog"] = 42
print d
- Get all keys (with dict.keys())
# Get all keys
d = dict([("dog", 10), ("ant", 0), ("cat", 3), ("cow", 7)])
print d.keys() # ['ant', 'dog', 'cow', 'cat']
print sorted(d.keys()) # ['ant', 'cat', 'cow', 'dog']
- Usage
- Can use mixed types for keys and values
# Can use mixed types for keys and values
d = { }
d["ant"] = True
d[False] = 42
d[999] = "gnu"
print d # {'ant': True, False: 42, 999: 'gnu'}
- Keys are case-sensitive
# Keys are case-sensitive
d = { }
d["ant"] = 3
d["Ant"] = 4
print d["ant"] # 3
print d["Ant"] # 4
d["cow"] = 32
print d["COW"] # crashes with KeyError, "COW" is not in the dictionary
- Don't use a dictionary like a list
# Don't use a dictionary like a list
# eg, the following code is discouraged:
def exampleOfIncorrectUseOfDictAsList():
d = { }
n = 4
print "Enter", n, "strings: "
for i in range(n):
value = raw_input("Enter string #" + str(i) + ": ")
d[i] = value
print "And here are the strings you entered:"
for i in range(n):
print i, d[i]
exampleOfIncorrectUseOfDictAsList()
- Recommended Reading
- http://docs.python.org/library/stdtypes.html#typesmapping
- http://docs.python.org/tutorial/datastructures.html
- http://diveintopython.org/getting_to_know_python/dictionaries.html
- Examples Using Dictionaries
- Word Counts (from a list of words) (wordCountsWithBug.py and wordCounts.py)
- Sparse Matrices (sparseMatrices.py)
- Text Adventure (textAdventure.py)
- Suggested Practice Problems
- More Sparse Matrix math (sparseMatrixAdd, sparseMatrixMultiply, sparseMatrixInverse, etc)
- contentsSortedByKey(dictionary):
Returns a list of the dictionary's key/value pairs (as tuples)
with the keys in alphabetical order
- contentsSortedByValue(dictionary): Returns a list of the dictionary's
key/value pairs (as tuples) with the values in alphabetical order (this is a bit trickier)
carpe
diem - carpe
diem - carpe
diem - carpe
diem - carpe
diem - carpe
diem - carpe
diem - carpe
diem - carpe diem