[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.")

Another Example:

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

  • Keys are unordered

  • Keys are unique

  • Keys must be immutable

3. Values are Unrestricted

5. Dictionaries are Very Efficient

As mentioned above, a dictionary's keys are stored as a set. This means that finding where a key is stored takes constant time. This lets us look up a dictionary's value based on a key in constant time too!

6. Some Worked Examples Using Dictionaries

  • mostFrequent(L)

  • isAnagram(s1, s2) video

Here we rewrite the 1d-list isAnagram example only using a dictionary instead.

Last updated

Was this helpful?