Essential Python

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

I’m Amr Abdelkarem, a PHP Backend Developer with 5+ years of experience building backend-driven systems using PHP, REST APIs, MySQL, and PostgreSQL. I’ve worked on e-commerce workflows, payment integrations, shipping automation, and scalable business logic in production environments. I also have previous experience with WordPress backend development and Django-based systems, and I’m currently focused on Laravel and backend architecture. My certifications include IBM’s Developing Front-End Apps with React, plus certifications in Cloud Computing, HTML/CSS/JavaScript, Software Engineering, Python for Data Science, and Databases and SQL.

No Comments

Leave a Comment

Course Recommendations