Python
Dictionaries & Sets
33 flashcards · answers and spaced-repetition review in the KnowCard app
What does this print?
```
d = {"a": 1, "a": 2}
print(d)
```
Why does this raise an error?
```
d = {[1, 2]: "x"}
```
Can a tuple be a dict key but a list cannot? Why the difference?
What does this print?
```
d = {1: "x"}
print(d[1.0])
```
What does this print?
```
d = {"a": 1, "b": 2}
print("a" in d)
print(1 in d)
```
What does this loop print?
```
d = {"a": 1, "b": 2}
for x in d:
print(x)
```
Are dict keys iterated in a guaranteed order? Since when?
What's the difference between d[k], d.get(k), and d.setdefault(k, x) for a missing key?
What does this print?
```
d = {"k1": "v1"}
print(d.get("k2", 99))
print(d)
```
What does this print?
```
a = {"x": 1, "y": 2}
b = {"y": 9, "z": 3}
print({**a, **b})
```
Which Python version added the | and |= merge operators for dicts, and what's the pre-3.9 way?
What does this print?
```
d = {"a": 1}
view = d.keys()
d["b"] = 2
print(list(view))
```
What happens?
```
d = {"a": 1, "b": 2}
for k in d:
if k == "a":
del d[k]
```
What does this print, and why is it a classic bug?
```
def f(k, cache={}):
cache[k] = k * k
return cache
f(2)
print(f(3))
```
What does this print?
```
a = {"x": 1, "y": 2}
b = {"y": 2, "x": 1}
print(a == b)
```
What does this print?
```
d = {"a": 1, "b": 2}
v = d.pop("a")
print(v, d)
```
What does this comprehension produce?
```
{k: len(k) for k in ["hi", "bye"]}
```
What does this print?
```
s = {1, 2, 2, 3, 3, 3}
print(len(s))
```
What's the difference between set add/update and discard/remove?
What does this print?
```
s = {1, 2, 3, 4, 5}
t = {4, 5, 6, 7}
print(s & t, s - t, s ^ t)
```
What does this print?
```
m = {1, 2, 3}
n = {1, 2, 3}
print(m <= n, m < n)
```
Why use frozenset, and what does the difference let you do?
After d.clear(), what is d — and how is that different from del d?
What does dict.fromkeys(["a", "b", "c"], 0) build, and what's the trap when the default value is mutable?
Do sets keep insertion order like dicts? Why might {'A', 'B', 'C'} print in a different order across separate runs?
What does this print?
print({1, 2, *[3, 4]})
Sets support |=, &=, -=, and ^=. What actually happens when you apply |= to a frozenset?
Which set operation is available as a method but has no operator equivalent, and what does it test?
What does this print?
print({1, 2, 3}.union("AB"))
print({1, 2, 3} | "AB")
Besides a {...} literal, what two call forms does the dict() constructor accept — and what restricts the keyword form?
What does this print?
d1 = {"k": [1, 2, 3]}
d2 = d1.copy()
d2["k"].append(4)
print(d1["k"])
What does popitem() return and remove from a dict, and what happens when the dict is empty?
What type is created by {} versus set()?
Start learning today
Free to start — download the app or use it in your browser.
