A dictionary in Python is like a real-life dictionary, it stores key-value pairs. You look up a key and get its value. It’s great for organizing data where each item has a label. It is a collection that is ordered, changeable, and most importantly, it does not allow duplicate keys—every “label” must be unique.
Creating a Dictionary
To create a dictionary, you wrap your data in curly braces{}. Inside, you pair a “Key” with a “Value” using a colon : and separate each pair with a comma. For example, if you were describing a car, the keys would be “brand” and “model,” and the values would be “Ford” and “Mustang.”
You can “get” the value of an item by putting its key name inside square brackets []. If you are worried that a key might not exist and don’t want your program to crash, you can use the .get() method, which will simply return “None” instead of an error if the key is missing.
# Accessing the model of the car x= my_car["model"] print(x) # Output: Mustang # Using the get() method y= my_car.get("year") print(y) # Output: 1964
Changing and Updating Items
Changing data in a dictionary is very straightforward; you just refer to the key name and assign it a new value. If you need to update several pieces of information at once, Python provides the .update() method, which allows you to merge new data into your existing dictionary easily.
# Changing the year my_car["year"] =2020 print(my_car) #output: {'make': 'Toyota', 'model': 'Corolla', 'year': 2020}
Adding a new item doesn’t require a special function; you just define a new key and give it a value, and Python automatically grows the dictionary. To remove items, you can use .pop() to remove a specific key, or the del keyword; if you want to empty the entire dictionary but keep the variable, the .clear() method is the best tool.
# Adding a new item
my_car["owner"] ="Alex"# Removing an item
my_car.pop("model")
Looping Through Dictionaries
When you loop through a dictionary, you have three choices: you can loop through just the keys, just the values, or both at the same time. By using the .items() method in a for loop, you can grab the “Label” and the “Data” simultaneously, which is perfect for printing out organized summaries of your information.
# Printing all keys and values forkey, valuein my_car.items(): print(f"{key}: {value}")
Dictionary Methods
Python includes a variety of built-in “short-cuts” or methods to make managing your dictionaries easier. Common methods include .keys() to see all your labels, .values() to see all your stored data, and .copy(), which creates a separate duplicate of your dictionary so you can experiment without changing the original data.
Method
Description
.keys()
Returns a list of all the keys in the dictionary.
.values()
Returns a list of all the values in the dictionary.
.items()
Returns a list of tuples for each key-value pair.
.popitem()
Removes the last inserted item.
Nested Dictionaries
A Nested Dictionary is essentially a dictionary that contains other dictionaries inside it. This is incredibly useful for organizing complex data, such as a “Company” dictionary that contains multiple “Employee” dictionaries, where each employee has their own specific set of details like name, ID, and department.