dict
Type¶to_words = {
0: "zero",
1: "one",
2: "two",
}
from_words = {
"zero": 0,
"one": 1,
"two": 2,
}
to_words
{0: 'zero', 1: 'one', 2: 'two'}
from_words
{'zero': 0, 'one': 1, 'two': 2}
dict([("zero", 0), ("one", 1), ("two", 2)])
{'zero': 0, 'one': 1, 'two': 2}
dict(zero=0, one=1, two=2)
{'zero': 0, 'one': 1, 'two': 2}
people = {
"mathematicians": [
{
"name": "Gilbert Strang",
"emails": ["gilbert@mit.edu"],
},
{
"name": "Leonhard Euler",
"emails": [],
},
],
"physicists": [],
"programmers": [
{
"name": "Guido",
"emails": ["guido@python.org", "guido@dropbox.com"],
},
],
}
people
{'mathematicians': [{'name': 'Gilbert Strang', 'emails': ['gilbert@mit.edu']}, {'name': 'Leonhard Euler', 'emails': []}], 'physicists': [], 'programmers': [{'name': 'Guido', 'emails': ['guido@python.org', 'guido@dropbox.com']}]}
from pprint import pprint
pprint(people, indent=1, width=60)
{'mathematicians': [{'emails': ['gilbert@mit.edu'], 'name': 'Gilbert Strang'}, {'emails': [], 'name': 'Leonhard Euler'}], 'physicists': [], 'programmers': [{'emails': ['guido@python.org', 'guido@dropbox.com'], 'name': 'Guido'}]}
{
["zero", "one"]: [0, 1],
}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[17], line 1 ----> 1 { 2 ["zero", "one"]: [0, 1], 3 } TypeError: unhashable type: 'list'
{
"zero": 0,
"one": 1,
"two": 2,
"zero": 999, # to illustrate a point
}
{'zero': 999, 'one': 1, 'two': 2}
Bucket | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
---|---|---|---|---|---|---|---|---|
Key | ... | ... | ... | ... | ... | ... | ... | ... |
Value | ... | ... | ... | ... | ... | ... | ... | ... |
hash("zero")
-85344695604937002
hash(0)
0
hash(1) == hash(1.0)
True
hash(["zero", "one"])
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[24], line 1 ----> 1 hash(["zero", "one"]) TypeError: unhashable type: 'list'
hash(("zero", "one"))
-1616807732336770172
{
("zero", "one"): [0, 1],
}
{('zero', 'one'): [0, 1]}
def buckets(mapping, *, bits):
"""Calculate the bucket indices for a mapping's keys."""
for key in mapping: # cf., next section for details on looping
hash_value = hash(key)
binary = bin(hash_value)
address = binary[-bits:]
bucket = int("0b" + address, base=2)
print(key, hash_value, "0b..." + binary[-8:], address, bucket, sep="\t")
buckets(from_words, bits=2)
zero -85344695604937002 0b...00101010 10 2 one 6414592332130781825 0b...10000001 01 1 two 4316247523642253857 0b...00100001 01 1
buckets(from_words, bits=3)
zero -85344695604937002 0b...00101010 010 2 one 6414592332130781825 0b...10000001 001 1 two 4316247523642253857 0b...00100001 001 1
buckets(from_words, bits=4)
zero -85344695604937002 0b...00101010 1010 10 one 6414592332130781825 0b...10000001 0001 1 two 4316247523642253857 0b...00100001 0001 1
len(from_words)
3
for word in from_words:
print(word)
zero one two
for word in reversed(from_words):
print(word)
two one zero
"one" in from_words
True
list
vs. dict
¶import random
needle = 42
haystack = [random.randint(99, 9999) for _ in range(10_000_000)]
haystack.append(needle)
random.shuffle(haystack)
haystack[:10]
[8126, 7370, 3735, 213, 7922, 1434, 8557, 9609, 9704, 9564]
%%timeit -n 1 -r 1
for _ in range(10):
needle in haystack
4.44 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
magic_haystack = dict((x, None) for x in haystack)
%%timeit -n 1 -r 1
for _ in range(10_000_000):
needle in magic_haystack
560 ms ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
from_words["two"]
2
from_words["drei"]
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[61], line 1 ----> 1 from_words["drei"] KeyError: 'drei'
people["mathematicians"]
[{'name': 'Gilbert Strang', 'emails': ['gilbert@mit.edu']}, {'name': 'Leonhard Euler', 'emails': []}]
people["mathematicians"][0]
{'name': 'Gilbert Strang', 'emails': ['gilbert@mit.edu']}
people["mathematicians"][0]["name"]
'Gilbert Strang'
people["mathematicians"][0]["emails"]
['gilbert@mit.edu']
to_words
{0: 'zero', 1: 'one', 2: 'two'}
to_words[0] = "null"
to_words[1] = "eins"
to_words[2] = "zwei"
to_words
{0: 'null', 1: 'eins', 2: 'zwei'}
to_words[3] = "drei"
to_words[4] = "vier"
to_words
{0: 'null', 1: 'eins', 2: 'zwei', 3: 'drei', 4: 'vier'}
del to_words[0]
to_words
{1: 'eins', 2: 'zwei', 3: 'drei', 4: 'vier'}
people["physicists"]
[]
people["physicists"].append({"name": "Albert Einstein"})
people["programmers"][0]
{'name': 'Guido', 'emails': ['guido@python.org', 'guido@dropbox.com']}
people["programmers"][0]["name"] = "Guido van Rossum"
del people["programmers"][0]["emails"][1]
pprint(people, indent=1, width=60)
{'mathematicians': [{'emails': ['gilbert@mit.edu'], 'name': 'Gilbert Strang'}, {'emails': [], 'name': 'Leonhard Euler'}], 'physicists': [{'name': 'Albert Einstein'}], 'programmers': [{'emails': ['guido@python.org'], 'name': 'Guido van Rossum'}]}
dict
Methods¶for word in from_words.keys():
print(word)
zero one two
for number in from_words.values():
print(number)
0 1 2
for word, number in from_words.items():
print(f"{word} -> {number}")
zero -> 0 one -> 1 two -> 2
to_words
{1: 'eins', 2: 'zwei', 3: 'drei', 4: 'vier'}
to_words.get(0, "n/a")
'n/a'
to_spanish = {
0: "cero",
1: "uno",
2: "dos",
3: "tres",
4: "cuatro",
5: "cinco",
}
to_words.update(to_spanish)
to_words
{1: 'uno', 2: 'dos', 3: 'tres', 4: 'cuatro', 0: 'cero', 5: 'cinco'}
from_words
{'zero': 0, 'one': 1, 'two': 2}
number = from_words.pop("zero")
number
0
from_words
{'one': 1, 'two': 2}
word, number = from_words.popitem()
word, number
('two', 2)
from_words
{'one': 1}
from_words.clear()
from_words
{}
dict
Comprehensions¶to_words = {
0: "zero",
1: "one",
2: "two",
}
from_words = {}
for number, word in to_words.items():
from_words[word] = number
from_words
{'zero': 0, 'one': 1, 'two': 2}
{v: k for k, v in to_words.items()}
{'zero': 0, 'one': 1, 'two': 2}