Python Python dict(): Create Dictionaries — Syntax, Literals vs Constructor, …
page info
name Goposu datetime⏰ 25-10-11 03:16 hit👁️ 12 comment💬 0text

Python dict(): Construct and work with dictionaries
The built-in dict()
function creates a dictionary—an unordered, mutable mapping of keys to values. Dictionaries are central to Python for configuration, JSON-like data, counting, caching, and fast lookups. This guide covers construction methods, key constraints, merging, defaults, comprehensions, and common pitfalls.
Syntax
dict() # empty dict
dict(mapping_or_iterable) # from mapping or key/value pairs
dict(**kwargs) # from keyword arguments
Parameters: A mapping (e.g., another dict
), an iterable of 2-item pairs (e.g., [("k","v"), ...]
), and/or keyword arguments.
Returns: A new dict
object.
Create dictionaries
# Literal
d1 = {"a": 1, "b": 2}
# Constructor from pairs
d2 = dict([("x", 10), ("y", 20)])
# Keyword arguments (keys must be valid identifiers)
d3 = dict(alpha=1, beta=2)
# From another mapping
d4 = dict(d1)
Keys, mutability, and hashing
- Valid keys: Keys must be hashable (e.g.,
str
,int
,tuple
of hashables).list
,dict
, and other mutable types are not allowed. - Uniqueness: Duplicate keys overwrite previous values during construction.
- Order: In modern Python, dict preserves insertion order (useful for predictable iteration).
# Hashable keys
ok = {(1, 2): "pair", "id": 42}
# Not hashable (TypeError)
# bad = {["a", "b"]: 1}
Access, update, and safe lookups
d = {"count": 3}
# Access
print(d["count"]) # 3
# Safe get with default
print(d.get("missing", 0)) # 0
# Update and set defaults
d["count"] = d.get("count", 0) + 1
d.setdefault("items", []).append("X") # initialize if absent
Merging and copying
- Union: Use
|
or{**a, **b}
to merge; right side wins on conflicts. - In-place update:
d.update(other)
modifiesd
. - Copies:
d.copy()
makes a shallow copy; usecopy.deepcopy()
for nested structures.
a = {"x": 1, "y": 2}
b = {"y": 9, "z": 3}
c = a | b # {'x': 1, 'y': 9, 'z': 3}
a.update({"w": 0}) # a becomes {'x': 1, 'y': 2, 'w': 0}
Comprehensions and transformations
Dict comprehensions build mappings from iterables and are ideal for filtering and projecting data.
nums = [("a", 1), ("b", 2), ("c", 3)]
d = {k: v for (k, v) in nums if v % 2 == 1} # {'a': 1, 'c': 3}
# Invert and transform
scores = {"alice": 88, "bob": 95}
inv = {v: k for k, v in scores.items()}
scaled = {k: v / 100 for k, v in scores.items()}
Common patterns
- Counting: Increment via
get
/setdefault
or usecollections.Counter
. - Grouping: Accumulate lists per key.
- Mapping JSON: Dictionaries mirror JSON objects for API payloads and configs.
# Counting occurrences
text = "banana"
freq = {}
for ch in text:
freq[ch] = freq.get(ch, 0) + 1
# Grouping by key
pairs = [("a", 1), ("a", 2), ("b", 3)]
groups = {}
for k, v in pairs:
groups.setdefault(k, []).append(v)
Pitfalls and caveats
- Keyword-only keys:
dict(a=1)
works, butdict({"a": 1}, b=2)
is fine whereasdict([("invalid-key", 1)])
is fine; keyword syntax requires valid identifiers (no spaces, hyphens). - Mutable defaults: Beware of shared lists/dicts across keys; create per-key containers with
setdefault
or comprehensions. - Shallow copies:
dict()
andcopy()
don’t copy nested structures; mutations inside nested objects affect all references.
# Keyword keys must be identifiers
d = dict(ok=1) # good
# d = dict(**{"not-valid-key": 1}) # works via ** but only if key is a valid identifier; otherwise avoid kwargs
Advanced features
- Views:
d.keys()
,d.values()
,d.items()
are dynamic views that reflect changes. - Defaultdict: For automatic defaults, use
collections.defaultdict
. - OrderedDict: Historically for order-sensitive logic; plain dict now preserves insertion order, but
OrderedDict
still offers move-to-end and equality semantics.
from collections import defaultdict
dd = defaultdict(list)
dd["k"].append(1) # auto-creates list
FAQ
- Is
dict()
different from{}
? - Both create dicts. Use
{}
for literals; usedict()
for constructing from pairs, mappings, or keyword args. - How do I avoid KeyError?
- Use
get()
,setdefault()
, or check presence within
(e.g.,if key in d:
). - How can I merge many dicts?
- Use
functools.reduce
with|
, a loop withupdate()
, or unpack with{**a, **b, **c}
.
Related keywords
Python dict, dictionary constructor, mapping, keys and values, merging, setdefault, defaultdict, comprehensions, JSON
👍good0 👎nogood 0
comment list 0
There are no registered comments.