SyntaxStudy
Sign Up
Python Beginner 8 min read

Dictionary Methods

Dictionary Methods

Python dicts come with rich methods for viewing, iterating, merging, and manipulating data.

View Objects

config = {"host": "localhost", "port": 5432, "db": "mydb"}
print(config.keys())    # dict_keys([...])
print(config.values())  # dict_values([...])
print(config.items())   # dict_items([...])

Iterating

for key in config:
    print(key, config[key])

for key, value in config.items():
    print(f"{key}: {value}")

get() / pop() / setdefault()

print(config.get("timeout", 30))   # 30 (default)
removed = config.pop("db", None)   # safe pop
config.setdefault("timeout", 30)   # set if not present
print(config["timeout"])           # 30

update()

config.update({"port": 3306, "db": "production"})
config.update(host="127.0.0.1")   # keyword form
print(config)

copy()

cfg2 = config.copy()   # shallow copy
cfg2["host"] = "remote"
print(config["host"])  # still "127.0.0.1"
Example
scores = {"Alice": 95, "Bob": 78, "Carol": 88}
for name, score in scores.items():
    grade = "A" if score >= 90 else "B" if score >= 80 else "C"
    print(f"{name}: {score} ({grade})")

scores.setdefault("Dave", 0)
scores["Alice"] = scores.get("Alice", 0) + 5
print(scores)
Pro Tip

dict.keys(), .values(), and .items() return view objects that reflect changes to the dict in real time — they are not snapshots.