Remember
dict() creates a mapping from keys to values. A later assignment to a key replaces its earlier value.
dict() creates a mapping from keys to values. A later assignment to a key replaces its earlier value.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
scores = dict(Ada=3, Ben=2)
print(scores)Top-level scope
{'Ada': 3, 'Ben': 2}dict() creates a mapping from keys to values. A later assignment to a key replaces its earlier value.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
scores = dict(Ada=3, Ben=2)
print(scores)
|
v
DISPLAYED RESULT
{'Ada': 3, 'Ben': 2}
FINAL BINDINGS
scores --> object 1 (dict)
object 1: {'Ada': 3, 'Ben': 2}Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
scores = dict(Ada=3, Ben=2)
print(scores)Top-level scope
{'Ada': 3, 'Ben': 2}The example has finished. Compare the final output with the values and references above.
{'Ada': 3, 'Ben': 2}
What do you expect this program to print?
scores = dict(Ada=3, Ben=2)
print(scores)dict() FunctionThe dict() function in Python is used to create a dictionary. A dictionary is an unordered collection of key-value pairs, where each key must be unique and immutable.
dict(**kwargs)
dict(mapping)
dict(iterable)
**kwargs – Key-value pairs as keyword arguments (e.g., name="Alice")mapping – Another dictionary or mapping objectiterable – An iterable with key-value pairs, like a list of tuplesd = dict()
print(d)
{}
person = dict(name="Alice", age=25)
print(person)
{'name': 'Alice', 'age': 25}
pairs = [("a", 1), ("b", 2)]
d = dict(pairs)
print(d)
{'a': 1, 'b': 2}
original = {'x': 10, 'y': 20}
copy = dict(original)
print(copy)
{'x': 10, 'y': 20}
dict(1="a") is invalid)The dict() function is often used to build frequency maps or group data. Understanding how to use dict() from tuples or with zip() is useful in many coding interviews.
dict() creates dictionaries from keyword arguments, mappings, or iterable pairsConvert two lists into a dictionary using dict() and zip():
keys = ["name", "age", "city"]
values = ["Alice", 25, "New York"]
result = dict(zip(keys, values))
print(result)
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Try changing the values and see how the dictionary updates!
Connect what you noticed in the example with the idea below.
dict() creates a mapping from keys to values. A later assignment to a key replaces its earlier value.
A dictionary permits multiple simultaneous values for the same key.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.