In [1]:
dct = dict()
print(type(dct), dct)
In [2]:
dct = {}
print(type(dct), dct)
In [3]:
dct = {'a': 1}
print(type(dct), dct)
In [4]:
dct['b'] = 2
dct
Out[4]:
In [5]:
dct['a'] = 3
dct
Out[5]:
In [6]:
dct['b']
Out[6]:
In [7]:
#dct['c']
#---------------------------------------------------------------------------
#KeyError Traceback (most recent call last)
#<ipython-input-12-3e4d85f12902> in <module>()
#----> 1 dct['c']
#
#KeyError: 'c'
In [8]:
len(dct)
Out[8]:
In [9]:
print('a' in dct)
print('c' in dct)
In [10]:
values = dct.values()
print(values)
In [11]:
def histogram(s: str) -> dict:
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
In [12]:
hist = histogram("This is a test and a Hello World".lower())
print(hist)
In [13]:
def histogram(s: str) -> dict:
d = dict()
for c in s:
d[c] = d.get(c, 0) + 1
return d
In [14]:
hist = histogram("This is a test and a Hello World".lower())
print(hist)
In [15]:
def print_histogram(dct: dict) -> None:
for key, value in dct.items():
print(key, value)
In [16]:
print_histogram(hist)
In [17]:
def print_histogram(dct: dict) -> None:
for key in sorted(dct):
print(key, dct[key])
In [18]:
print_histogram(hist)
In [19]:
def print_histogram(dct: dict) -> None:
for key, value in sorted(dct.items()):
print(key, value)
In [20]:
print_histogram(hist)
In [21]:
def reverse_lookup(dct: dict, value: int) -> str:
for key in dct:
if dct[key] == value:
return key
else:
raise LookupError('value does not appear in the dictionary')
In [22]:
print(reverse_lookup(histogram('parrot'), 2))
In [23]:
#print(reverse_lookup(histogram('parrot'), 3))
#---------------------------------------------------------------------------
#LookupError Traceback (most recent call last)
#<ipython-input-45-0d81dc02c5ce> in <module>()
#----> 1 print(reverse_lookup(histogram('parrot'), 3))
#
#<ipython-input-43-dcc62d669299> in reverse_lookup(dct, value)
# 4 return key
# 5 else:
#----> 6 raise LookupError('value does not appear in the dictionary')
#
#LookupError: value does not appear in the dictionary
In [24]:
known = {0:0, 1:1}
def fibonacci(n: int) -> int:
if n in known:
return known[n]
res = fibonacci(n-1) + fibonacci(n-2)
known[n] = res
return res
In [25]:
for i in range(10):
print("fib({}): {}".format(i, fibonacci(i)))
print(known)