[course]06 dictionary
1. Quick Example
# A dictionary is a data structure that maps keys to values in the same way
# that a list maps indexes to values. However, keys can be any immutable value!
stateMap = { 'pittsburgh':'PA', 'chicago':'IL', 'seattle':'WA', 'boston':'MA' }
city = input("Enter a city name --> ").lower()
if (city in stateMap):
print(city.title(), "is in", stateMap[city])
else:
print("Sorry, never heard of it.")counts = dict()
while True:
n = int(input("Enter an integer (0 to end) --> "))
if (n == 0): break
if (n in counts):
counts[n] += 1
else:
counts[n] = 1
print("I have seen", n, "a total of", counts[n], "time(s)")
print("Done, counts:", counts)2. Creating Dictionaries
1. Create an empty dictionary
2. Create a dictionary from a list of (key, value) pairs
3. Statically-allocate a dictionary
3. Using Dictionaries
4.Properties of Dictionaries
1. Dictionaries Map Keys to Values
2. Keys are Sets
3. Values are Unrestricted
5. Dictionaries are Very Efficient
6. Some Worked Examples Using Dictionaries
Last updated