๐ Python Dictionary Cheat Sheet


๐ Python Dictionary Cheat Sheet
๐ง Creating Dictionaries
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
empty_dict = {}
alt_dict = dict(name="Bob", age=30)
๐ Accessing Values
my_dict["name"] # Get value by key
my_dict.get("age") # Get with default fallback
โ Adding / Updating Items
my_dict["email"] = "alice@example.com" # Add new key-value
my_dict["age"] = 26 # Update value
my_dict.update({"city": "Boston", "job": "Engineer"}) # Multiple updates
โ Removing Items
my_dict.pop("age") # Remove by key
del my_dict["city"] # Delete key
my_dict.popitem() # Remove last inserted item
my_dict.clear() # Remove all items
๐ Looping Through Dictionary
for key in my_dict:
print(key, my_dict[key])
for key, value in my_dict.items():
print(key, value)
๐ Checking Keys
"name" in my_dict # Check if key exists
"email" not in my_dict # Check if key does NOT exist
๐ Dictionary Methods
my_dict.keys() # Get all keys
my_dict.values() # Get all values
my_dict.items() # Get key-value pairs
๐งฑ Dictionary Comprehension
squares = {x: x*x for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
๐งช Copying a Dictionary
new_dict = my_dict.copy() # Shallow copy
new_dict = dict(my_dict) # Another way
โ๏ธ Merging Dictionaries (Python 3.9+)
dict1 = {"a": 1}
dict2 = {"b": 2}
merged = dict1 | dict2 # Combine dictionaries
Subscribe to my newsletter
Read articles from David Gostin directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

David Gostin
David Gostin
Full-Stack Web Developer with over 25 years of professional experience. I have experience in database development using Oracle, MySQL, and PostgreSQL. I have extensive experience with API and SQL development using PHP and associated frameworks. I am skilled with git/github and CI/CD. I have a good understanding of performance optimization from the server and OS level up to the application and database level. I am skilled with Linux setup, configuration, networking and command line scripting. My frontend experience includes: HTML, CSS, Sass, JavaScript, jQuery, React, Bootstrap and Tailwind CSS. I also have experience with Amazon EC2, RDS and S3.