 PROGRAMMING

# m9/ PYTHON REMEMBERS

Last update:   23-07-2021

### Dictionaries

p187 ! In a list, the index have to be integer, in a dictionary it can be any type. A dictonary represents a mapping from keys to values eng2sp = dict()  # creates an empty dictionary
eng2sp["one"] = "uno"

eng2sp = {  # creates a dictionary using {}
"one": "uno",
"two": "dos",
"three": "tres",
}

print(eng2sp["two"])  # dos
... 2 lines 
p189 The in operator works on dictionaries, too. eng2sp = {
"one": "uno",
"two": "dos",
"three": "tres",
}

print("one" in eng2sp)  # True

p190 Suppose you have a string and you want to count how many times each letter appears. def histogram(str):
d = dict()
for c in str:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d

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

# histogram:
# the statistical term for a collection of counters
... 5 lines 
Value    (2/3)

### VALUE

p191 The get method takes a key and a default value. If the key appears in dictionary, it returns the corresponding value. def histogram(str):
d = dict()
for c in str:
d[c] = d.get(c, 0) + 1  # Look Here
return d

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

p192 A for statement traverses the keys of the dictionaries. The keys are in no order, use sorted if you need that. def histogram(str):
d = dict()
for c in str:
d[c] = d.get(c, 0) + 1
return d

def histogram_print(h):
for key in h:
print(key, h[key])

# g 2
# o 2
# l 1
# e 1
... 7 lines 
Key    (3/3)

### KEY

p193 What if you have value and want to find key? For a reverse lookup (to find key) there is no simple syntax, you have to search. def histogram(str):
d = dict()
for c in str:
d[c] = d.get(c, 0) + 1
return d

def reverse_lookup(d, value):
for key in d:
if d[key] == value:
return key
raise LookupError

key = reverse_lookup(h, 2)
print(key)  # g
... 7 lines 
p195 You might want to invert it, to map the frequencies to letters. def histogram(str):
d = dict()
for c in str:
d[c] = d.get(c, 0) + 1
return d

def histogram_print(h):
for key in h:
print(key, h[key])

def invert_dic(d):
d2 = dict()
for key in d:
value = d[key]
if value not in d2:
d2[value] = [key]  # new row list
else:
d2[value].append(key)  # add to row list
return d2

h2 = invert_dic(h)
histogram_print(h2)
# 2 ['g', 'o']
# 1 ['l', 'e']
... 16 lines 

### Hash

p197 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. The keys have to be hashable and mutable types like lists aren't. list = ['a', 'b', 'c']

dict = {
list: 'a'
}

print(dict) # TypeError: unhashable type: 'list'


Questions

A B C D E F
🔔
1/1