Python6 min read

Python Dictionary Methods

Master all important dictionary methods in Python.

Michael Brown
December 18, 2025
0.0k0

All important dictionary operations.

Getting Values

```python person = {"name": "Tom", "age": 25, "city": "Austin"}

Get value print(person.get("name")) # Tom print(person.get("email", "N/A")) # N/A (default)

Get all keys print(person.keys()) # dict_keys(['name', 'age', 'city'])

Get all values print(person.values()) # dict_values(['Tom', 25, 'Austin'])

Get key-value pairs print(person.items()) # dict_items([('name', 'Tom'), ...]) ```

Adding/Updating

```python person = {"name": "Tom"}

Add single person["age"] = 25

Update multiple person.update({"city": "Austin", "age": 26}) print(person) ```

Removing Items

```python person = {"name": "Tom", "age": 25, "city": "Austin"}

Remove and return value age = person.pop("age") print(age) # 25 print(person) # {'name': 'Tom', 'city': 'Austin'}

Remove last item (Python 3.7+) item = person.popitem() print(item) # ('city', 'Austin')

Clear all person.clear() print(person) # {} ```

Setdefault

```python person = {"name": "Tom"}

Get or set default age = person.setdefault("age", 25) print(age) # 25 print(person) # {'name': 'Tom', 'age': 25} ```

Copy Dictionary

```python original = {"name": "Tom", "age": 25}

Shallow copy copy = original.copy()

Another way copy2 = dict(original) ```

Merge Dictionaries

```python dict1 = {"name": "Tom", "age": 25} dict2 = {"city": "Austin", "age": 26}

Python 3.9+ merged = dict1 | dict2 print(merged) # {'name': 'Tom', 'age': 26, 'city': 'Austin'}

Older way merged = {**dict1, **dict2} ```

Remember

- Use get() for safe access - update() for multiple items - pop() returns removed value

#Python#Intermediate#Dictionaries