Essential Python

Python Dictionary Methods Cheatsheet: All You Need to Know

Python dictionaries are one of the most powerful and flexible data types you’ll use. Whether you’re storing user data, configurations, or API responses, knowing how to manipulate dictionaries is essential.

This cheatsheet covers the most used dictionary methods, each with a quick explanation and example.

🧠 What is a Dictionary in Python?

A dictionary is a collection of key-value pairs, declared like this:

q = {'NAME': 'John', 'AGE': 43}

🔍 Python Dictionary Methods (with Examples)

🔹 get()

Returns the value for the specified key. If the key is not found, returns None.

q.get('NAME')  # Output: 'John'

🔹 keys()

Returns a view of all the keys in the dictionary.

q.keys()  # Output: dict_keys(['NAME', 'AGE'])

🔹 values()

Returns a view of all the values in the dictionary.

q.values()  # Output: dict_values(['John', 43])

🔹 update()

Updates the dictionary with new key-value pairs.

q.update({'STATE': 'CA'})
# Result: {'NAME': 'John', 'AGE': 43, 'STATE': 'CA'}

🔹 items()

Returns a view of all key-value pairs as tuples.

q.items()
# Output: dict_items([('NAME', 'John'), ('AGE', 43)])

🔹 setdefault()

Returns the value of a key. If the key doesn’t exist, it adds it with a default value.

q.setdefault('PIN', 58796)
# Result: {'NAME': 'John', 'AGE': 43, 'STATE': 'CA', 'PIN': 58796}

🔹 pop()

Removes the key and returns its value.

q.pop('STATE')
# Output: 'CA'

🔹 popitem()

Removes and returns the last inserted key-value pair.

q.popitem()
# Output: ('PIN', 58796)

🔹 clear()

Removes all key-value pairs from the dictionary.

q.clear()
# Result: {}

🧪 Bonus Tip: Use in to Check Key Existence

'NAME' in q  # Output: True
Python Dictionary Cheatsheet

🎓 Learn Python from Scratch

Master Python programming with these beginner-to-pro courses:

🔗 Meta Data Analyst Professional Certificate
🔗 Microsoft Python Development Certificate
🔗 Google IT Automation with Python

📘 Visit programmingvalley.com for more free Python guides, infographics, and roadmaps.

Amr Abdelkarem

About me

No Comments

Leave a Comment