DEV Community

qing
qing

Posted on • Edited on

Master 14 Python Dict Methods

Python Dictionary Methods Cheatsheet

Everything you need to know about Python dictionaries in one place.

Dictionary Methods

Method Description Example
get(key, default) Safe key access d.get("x", 0)
keys() Get all keys d.keys()
values() Get all values d.values()
items() Get key-value pairs d.items()
update(other) Merge dicts d.update({"b": 2})
pop(key) Remove & return d.pop("a")
setdefault(k, v) Set if missing d.setdefault("x", [])
copy() Shallow copy d.copy()
clear() Remove all d.clear()

Code Examples

# Creating dictionaries
user = {"name": "Alice", "age": 30, "city": "NYC"}

# Safe access (avoid KeyError)
name = user.get("name", "Unknown")  # "Alice"
phone = user.get("phone", "N/A")    # "N/A"

# Iterating
for key, value in user.items():
    print(f"{key}: {value}")

# Dictionary comprehension
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Merging (Python 3.9+)
defaults = {"theme": "dark", "lang": "en"}
settings = {"lang": "zh"} | defaults  # lang="zh" wins

# Nested dict operations
data = {"users": {}}
data["users"].setdefault("alice", []).append("admin")

# Convert to sorted
sorted_dict = dict(sorted(user.items()))

# Filter dictionary
adults = {k: v for k, v in {"a": 25, "b": 17, "c": 30}.items() if v >= 18}
Enter fullscreen mode Exit fullscreen mode

Follow me for more Python cheatsheets! 🐍

Follow for more Python content!


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*


📚 Recommended Resources


喜欢这篇文章?关注获取更多Python自动化内容!

Top comments (0)