Dictionaries

A dictionary is like a list, but more general. In a list, the indices have to be integers, in a dictionary they can be (almost) any type.

# Declare empty dictionary
eng2sp = {}¬
¬
# Setting key of "one" to uno
eng2sp['one'] = 'uno'¬
¬
print(eng2sp)
name_to_age_map = {}
name_to_age_map["Don"] = 36
name_to_age_map["Ali"] = 29

# Retreive all the keys with .keys()
print(name_to_age_map.keys())

# Retreive all the values with .values()
print(name_to_age_map.values())

# Return a list of tuples with all k/v pairs in the dictionary .items()
print(name_to_age_map.items())

# Check if a key is in the dictionary using O(1) time.
# True
print("Don" in name_to_age_map)
# False
print("Ali" in name_to_age_map)

# Check if a value for a given key in O(1) time. Will return None if key is not
# in dictionary
print(name_to_age_map.get("Ali"))
print(name_to_age_map.get("Don"))

# This will throw an exception because "Ali" is a key that doesn't exist.
# name_to_age_map["Ali"]

# Do not do this, this is a O(n) search for all item sin the list for a key
# "Don"
print("Don" in name_to_age_map.keys())