Dictionaries

 
# ---------------------------------------
# DICTIONARIES
# ---------------------------------------
# A dictionary maps KEYS and VALUES.
# Unlinke lists, keys do NOT have to be integers.
# Keys must be unique and hashable.


# Create an empty dictionary
# --------------------------
prices = dict()

# Add items (product -> price)
prices["apple"] = 0.50
prices["banana"] = 0.30

# Access values using the key
assert prices.get("apple") == 0.50
assert prices.get("orange") == None  # key not found


# Create a dictonary using {}
# ---------------------------
prices = {
    "apple": 0.50,
    "banana": 0.30,
    "orange": 0.80,
}

assert prices["banana"] == 0.30
assert prices["orange"] == 0.80


# ----------------------------------
# CHECKING KEYS
# ----------------------------------

assert "apple" in prices
assert "grape" not in prices


# ----------------------------------
# LOOPING
# ----------------------------------

# Loop througk values
for price in prices.values():
    print(price)
    # 0.5
    # 0.3
    # 0.8

# Loop through keys
for product in prices.keys():
    print(product)
    # apple
    # banana
    # orange

# Loop through keys and values together
for product, price in prices.items():
    print(product, "costs", price)
    # apple costs 0.5
    # banana costs 0.3
    # orange costs 0.8

Histogram

 
# -------------------------------
# HISTOGRAM
# -------------------------------
# Problem:
# You have a text input and want to know:
#   - How many times does each character appear?
#
# A histogram counts how many times each item apperas.
# 
# get() avoids errors when the key is missing.

def histogram(text):
    """
    Counts how many times each character appears.
    Returns a dictionary: character -> count
    """
    counts = dict()

    for ch in text:
        if ch not in counts:
            counts[ch] = 1
        else:   
            counts[ch] += 1

    return counts

assert histogram("google") == {'g': 2, 'o': 2, 'l': 1, 'e': 1}


# -------------------------------------
# get(key, default)
# -------------------------------------

h = histogram("yahoo")

assert h.get('o') == 2
assert h.get('x', 0) == 0  # default value if key does not exists


# ---------------------------------------
# PRINTING RESULTS
# ---------------------------------------

h = histogram("google")

for letter in h:  # OR h.keys()
    print(letter + ": " + str(h[letter]))
    # g: 2
    # o: 2
    # l: 1
    # e: 1


# ----------------------------------------
# INVERT HISTOGRAM
# ----------------------------------------
# Turns: letter -> count
# Into: count -> letter

def invert_histogram(d):
    inverted = dict()

    for key in d:
        value = d[key]

        if value not in inverted:
            inverted[value] = [key]
        else:
            inverted[value].append(key)

    return inverted

h = invert_histogram(histogram("google"))

for count in h:
    print(count, h[count])
    # 2 ['g', 'o']
    # 1 ['l', 'e']

Hashing Dictionary

 
# --------------------------------------------
# HASHING (DICTIONARY
# --------------------------------------------
# A hash is a function that takes a value (on any kind) and returns an integer.
# Dictionaries use these integers to store and look up key-value pairs.
#
# Dictionary keys must be hashable.
# Mutable types (like lists) are NOT.

data = {}

data["one"] = 1
data[1] = "abc"

print(data)
# {'one': 1, 1: 'abc'}


# ---------------------------
# Unhasable types (ERROR)

items = [1, 2]
# data[items] = 3

# TypeError: unhashable type: 'list'
# List can change - dictionaries need keys that never change




References: