← Back to Blog

Dicts — The Full Picture

You've covered dicts from every angle. Before moving on, here's everything in one place.

// Creating dicts

{"key": value}             # literal
{}                         # empty dict
dict()                     # empty dict
dict(key=value)            # keyword arguments
dict(zip(keys, values))    # from two lists
d["key"] = value           # add or update a key

// Reading values

d["key"]                   # direct — KeyError if missing
d.get("key")               # safe — None if missing
d.get("key", default)      # safe — default if missing
"key" in d                 # True if key exists
"key" not in d             # True if key missing

// Modifying

d["key"] = value           # add or update
d.update(other)            # merge dict in
d.update(key=value)        # update with keyword args
d.setdefault("key", val)   # add only if missing
d.pop("key")               # remove, return value
d.pop("key", default)      # remove, return default if missing
d.popitem()                # remove, return last pair
d.clear()                  # empty the dict

// Inspecting

len(d)                     # number of key-value pairs
d.keys()                   # view of all keys
d.values()                 # view of all values
d.items()                  # view of all (key, value) pairs
val in d.values()          # True if value exists
d.copy()                   # independent copy

// Iterating

for key in d:              # keys only
for key in d.keys():       # keys — explicit
for val in d.values():     # values only
for k, v in d.items():     # key-value pairs — most common

// Nested dicts

roster = {
    "Raven": {"score": 85, "active": True},
    "Wolf":  {"score": 74, "active": False}
}
roster["Raven"]            # inner dict
roster["Raven"]["score"]   # value inside inner dict
roster["Raven"]["rank"] = "Sergeant"   # add inner key

for name, data in roster.items():
    print(name, data["score"])

// Common mistakes

d["missing"]               # KeyError — use get() or check with in
d = d.update({...})        # None — don't assign modifying methods
backup = d                 # same dict — use d.copy()
x in d                     # checks keys only — use x in d.values()
{"k": 1, "k": 2}           # duplicate key — last wins, no error
del d[k] in loop           # RuntimeError — build new dict instead
d.pop("k")                 # KeyError if missing — use d.pop("k", default)
{}                         # empty dict — not empty set (use set())

That's dicts. Key, value, instant lookup — and a full set of tools to work with them.

The cheatsheet above is yours to download and keep.

[ login to bookmark ] // copied! 18 views · 1 min
// resources
Cheatsheet Dicts — The Full Picture
← prev Common Dict Mistakes next → This One's Yours — Dicts
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.