dict() is flexible about its input: calling it with keyword arguments builds a dictionary directly from them, calling it on an existing dict copies that mapping, and calling it on any iterable of 2-item pairs — including the output of zip() — builds one from those pairs. Since Python 3.7, dicts preserve insertion order as a language guarantee, not just an implementation detail.
1Understanding dict()
dict() is flexible about its input: calling it with keyword arguments builds a dictionary directly from them, calling it on an existing dict copies that mapping, and calling it on any iterable of 2-item pairs — including the output of zip() — builds one from those pairs. Since Python 3.7, dicts preserve insertion order as a language guarantee, not just an implementation detail.
dict(zip(keys, values)) is the standard idiom for combining two parallel lists into a dictionary.
person = dict(name="Alice", age=30)
print(person)2Practical Example
Here is a real-world application of dict() showing how it is used in production Python code.
keys = ["a", "b", "c"]
values = [1, 2, 3]
combined = dict(zip(keys, values))
print(combined)3Best Practices
Follow these guidelines when working with dict():
1. Use dict.get(key, default) instead of direct key access when the key might be missing, to avoid a KeyError
2. Use dict(zip(keys, values)) to build a dict from two parallel sequences
3. Prefer a dict literal over dict() with keyword arguments when keys aren't valid Python identifiers, since keyword arguments require identifier-like keys
Tip: dict(zip(keys, values)) is the standard idiom for combining two parallel lists into a dictionary.
person = dict(name="Alice", age=30)
print(person)