In Python, dictionaries are a versatile and powerful data structure that allows you to store and retrieve data using key-value pairs. Unlike lists or tuples, which use numerical indices to access elements, dictionaries use keys as unique identifiers. This makes dictionaries incredibly handy when you need to map values to specific keys or perform efficient lookups.
Creating a dictionary is really simple; you use curly braces {}
and separate each key-value pair with a colon. For example
my_dict = {'key1': value1, 'key2': value2, 'key3': value3}.
This fundamental concept of dictionaries in Python forms a cornerstone for various operations across programming tasks. Now, We’ll learn the ropes of CRUD operations utilizing their built-in methods.
Creating Dictionaries
Python Dictionaries are data structures that store key-value pairs. There are several ways to create dictionaries in Python
- Curly Braces {} with Key-Value Pairs
The most common way to create a dictionary is by using curly braces to enclose key-value pairs separated by colons
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
# {'name': 'John Doe', 'age': 30, 'city': 'New York'}
2. Using a List Comprehension
You can use a list comprehension to create a dictionary from a list of key-value pairs. This is useful when you want to transform or filter elements before creating the dictionary:
keys = ["name", "age", "city"]
values = ["Alice Johnson", 28, "Los Angeles"]
person = {key: value for key, value in zip(keys, values)}
# {'name': 'Alice Johnson', 'age': 28, 'city': 'Los Angeles'}
3. Dictionary Comprehension
Similar to list comprehensions, you can also create dictionaries using dictionary comprehensions. This involves creating a new dictionary by specifying both keys and values in a concise manner:
keys = ["name", "age", "city"]
values = ["Michael Brown", 35, "Chicago"]
person = {keys[i]: values[i] for i in range(len(keys))}
# {'name': 'Michael Brown', 'age': 35, 'city': 'Chicago'}
4. dict() Constructor
You can use the built-in dict()
constructor to create a dictionary from a sequence of key-value pairs or from another dictionary
dict(name="Jane Smith", age=25, city="San Francisco")
# {'name': 'Jane Smith','age': 25, 'city': 'San Francisco'}
You can also create a dictionary from a list of tuples using the dict()
constructor:
dict([
("name", "Alice"),
("age", 30),
("occupation", "Engineer")
])
# {'name': 'Alice', 'age': 30, 'occupation': 'Engineer'}
5. Using the fromkeys()
Method
The fromkeys()
method creates a new dictionary with specified keys and a default value for each key:
syntax : dictionary.fromkeys(keys, value)
value
— Optional. The value for all keys. Default value is None
# Using the fromkeys() method
keys = ["name", "age"]
default_value = "Not Available"
dict.fromKeys(keys) #{'name': None, 'age': None}
dict.fromkeys(keys, default_value) # {'name': 'Not Available', 'age': 'Not Available'}
6. Using the zip()
Function
The zip()
function can be used to combine two or more sequences into pairs, which can then be used to create a dictionary:
keys = ["name", "age", "city"]
values = ["Sophia Williams", 22, "Houston"]
dict(zip(keys, values))
# {'name': 'Sophia Williams', 'age': 22, 'city': 'Houston'}
Reading Dictionaries
Next, moving on to reading data in Python dictionaries, you have various methods to access values
- Using Square Brackets [ ]
You can access values from a dictionary by using the keys as the index within square brackets
countries = {
"USA": "New York",
"Japan": "Tokyo",
"France": "Paris"
}
countries["USA"] # New York
countries["Japan"] # Tokyo
countries["France"] # Paris
person.name # This will result in an AttributeError
2. Using the get()
Method
The get()
method allows you to retrieve a value from a dictionary using a key. It also provides a default value if the key is not present
syntax : dictionary.get(keyname, value)
value
— Optional. A value to return if the specified key does not exist.
Default value Non
cities = {
"Germany": "Berlin",
"China": "Beijing"
}
cities.get("Germany") # Berlin
cities.get("India") # None if default value isn't provided
cities.get("USA", "City not found") # "City not found"
3. Using the keys()
and values()
Methods
The keys()
method returns a list of all keys in the dictionary, while the values()
method returns a list of all values. These methods can be useful when you only need to work with keys or values
syntax : dictionary.keys()
and dictionary.values()
countries = {
"Mexico": "Mexico City",
"United Kingdom": "London",
"Russia": "Moscow"
}
countries.keys() # dict_keys(['Mexico', 'United Kingdom', 'Russia'])
countries.values() # dict_values(['Mexico City', 'London', 'Moscow'])
4. Using the items()
Method:
The items()
method returns a list of tuples, where each tuple consists of a key and its corresponding value. You can use this method to iterate over both keys and values
countries = {
"Canada": "Toronto",
"Italy": "Rome"
}
countries.items() # dict_items([('Canada', 'Toronto'), ('Italy', 'Rome')])
5. Using a Loop (for…in)
You can iterate through the keys of a dictionary and retrieve their corresponding values using a loop
countries = {
"Brazil": "Rio de Janeiro",
"Australia": "Sydney"
}
for country in countries:
city = countries[country]
print(f"The city in {country} is {city}")
# The city in Brazil is Rio de Janeiro
# The city in Australia is Sydney
Updating Dictionaries
Python dictionaries are mutable, which means you can update their content after they’ve been created. Here are the various ways you can update dictionaries
# dictionary with car information
car = {
"make": "Toyota",
"model": "Camry",
"year": 2020
}
# {'make': 'Toyota', 'model': 'Camry', 'year': 2020}
- Using Square Brackets [ ]
You can use square brackets to update or add values to a dictionary by directly assigning a value to a specific key
car["year"] = 2021 # update an existing value
car["color"] = "Blue" # or make a new one
# car = {'make': 'Toyota', 'model': 'Camry', 'year': 2021, 'color': 'Blue'}
2. Using the update()
Method
The update()
method allows you to merge the content of one dictionary into another. It can take either another dictionary or an iterable of key-value pairs as an argument:
additional_data = {
"year": 2022, # Update year
"mileage": 15000 # Add mileage
}
car.update(additional_data)
# car = {'make': 'Toyota', 'model': 'Camry', 'year': 2022, 'mileage': 15000}
Remember that if you try to update a key that doesn’t exist using the square brackets approach, Python will add that key with the assigned value. However, if you use the update()
method, the method will not create new keys
. It's also important to note that dictionary keys are unique, so attempting to add a duplicate key will overwrite the existing value.
3. Using the setdefault()
Method
The setdefault()
method is used to insert a key with a default value if it doesn't exist in the dictionary. This method also used to read the data. It returns the value of the key, whether it was newly inserted or already existed.
car.setdefault("year",2023) #return 2020 since its alreay in the dictioanry
car.setdefault("previous_owners", 2) # Adding a new key with a default value
# car = {'make': 'Toyota', 'model': 'Camry', 'year': 2020, 'previous_owners': 2}
4. Using the dict()
Constructor
You can also create a new dictionary by merging two or more dictionaries or key-value pairs using the dict()
constructor
new_data = {
"model": "Corolla", # Update model
"color": "Red" # Update color
}
updated_car = dict(car, **new_data)
car # {'make': 'Toyota', 'model': 'Camry', 'year': 2020}
updated_car # {'make': 'Toyota', 'model': 'Corolla', 'year': 2020, 'color': 'Red'}
5. Using the .union()
method
The union of two dictionaries refers to combining the keys and values from both dictionaries into a single dictionary. Python 3.9 introduced the |
operator as a shorthand for dictionary union. Here's how you can use both the .union()
method and the |
operator
# Original dictionaries
car_data_one = {
"make": "Toyota",
"model": "Camry"
}
car_data_two = {
"model": "Corolla",
"color": "Blue"
}
union_car_data = car_data_one | car_data_two
# or car_data_one.union(car_data_two)
union_car_data # {'make': 'Toyota', 'model': 'Corolla', 'color': 'Blue'}
Deleting Dictionaries
Every creation is susceptible to destruction, and this applies even to Python dictionaries. Here are the methods to accomplish this
groceries = {"apples": 5, "bananas": 10, "bread": 2}
- Using the
del
Statement
You can use the del
statement to completely delete a dictionary or to delete a specific key-value pair
del groceries["bananas"] # Delete the "bananas" key and its value
groceries # {'apples': 5, 'bread': 2}
del groceries # Delete the entire 'groceries' dictionary
groceries # NameError: name 'groceries' is not defined
2. Using the clear()
Method
The clear()
method is used to remove all key-value pairs from a dictionary, effectively emptying it
groceries.clear() # Removes all key-value pairs from the 'groceries'
groceries # {}
3. Using the pop()
Method
The pop()
method is used to remove a key from a dictionary and return its associated value. You can provide a default value if the key doesn't exist
syntax dictionar.pop(keyname, defaultvalue)
defaultvalue
Optional. A value to return if the specified key do not exist.
If this parameter is not specified, and the no item with the specified key is found, an error is raised
# Remove "bananas" key and get its value
groceries.pop("bananas") # 10
# Remove nonexistent key with default value 0
groceries.pop("nonexistent_key", 0) # 0
# Remove nonexistent key without default value
groceries.pop("nonexistent_key") # KeyError: 'nonexistent_key'
4. Using the popitem()
Method
The popitem()
method removes and returns an arbitrary key-value pair from the dictionary. This is useful when you want to remove items from the dictionary in LIFO (Last In, First Out) order
In versions before 3.7, the popitem()
method removes a random item.
syntax dictionary.popitem()
groceries.popitem() # groceries.popitem()
# what if dictionary is empty
empty_dict = {}
empty_dict.popitem() # groceries.popitem()
Copying Dictionaries
Much like a scribe meticulously copying ancient manuscripts, you can create a duplicate of Python dictionaries using various methods
pokemons = {"Pikachu": "Electric", "Charmander": "Fire", "Squirtle": "Water"}
- Using the
copy()
Method
The copy()
method creates a shallow copy of the dictionary, which means that the keys and values are copied, but if the values themselves are mutable objects (like lists), the references to those objects are copied, not the objects themselves
clone = pokemons.copy() # {'Pikachu': 'Electric', 'Charmander': 'Fire', 'Squirtle': 'Water'}
# updating the values affects both the dict
clone['Pikachu'] = "Grass"
pokemons # {'Pikachu': 'Electric', 'Charmander': 'Fire', 'Squirtle': 'Water'}
clone # {'Pikachu': 'Grass', 'Charmander': 'Fire', 'Squirtle': 'Water'}
# effect of swallow copy
pokemons = { 0 : ["Pikachu","Electric"], 1 : ["Charmander","Fire"]}
clone = pokemons.copy() # try using copy.deepcopy() instead
clone[0][1] = "Grass"
pokemons # {0: ['Pikachu', 'Grass'], 1: ['Charmander', 'Fire']}
clone # {0: ['Pikachu', 'Grass'], 1: ['Charmander', 'Fire']}
2. Using the dict()
Constructor
You can create a new dictionary by passing an existing dictionary to the dict()
constructor. This creates a new dictionary with the same key-value pairs
# which doesn't have any side effects like copy()
clones = dict(pokemons) # {'Pikachu': 'Electric', 'Charmander': 'Fire', 'Squirtle': 'Water'}
3. Using Dictionary Comprehension
You can create a copy of a dictionary using dictionary comprehension. This method allows you to filter or transform the keys and values during the copying process
# Has the same behaviour like copy()
# that is, it performs shallow copy
clones = {name: type for name, type in pokemons.items()}
# {'Pikachu': 'Electric', 'Charmander': 'Fire', 'Squirtle': 'Water'}
4. Using Dictionary Unpacking
You can create a copy of a dictionary by unpacking its key-value pairs into a new dictionary and its performs shallow copy
# it performs shallow copy
clones = {**pokemons} # {'Pikachu': 'Electric', 'Charmander': 'Fire', 'Squirtle': 'Water'}
5. Using the copy()
Method with Nested Objects
If your dictionary contains mutable objects (like lists), and you want to create a true independent copy (deep copy), you can use the copy.deepcopy()
function from the copy
module
import copy
pokemons = { 0 : ["Pikachu","Electric"], 1 : ["Charmander","Fire"]}
clone = copy.deepcopy(pokemons)
clone[0][1] = "Grass"
pokemons # {0: ['Pikachu', 'Electric'], 1: ['Charmander', 'Fire']}
clone # {0: ['Pikachu', 'Grass'], 1: ['Charmander', 'Fire']}
Absolutely! 🪄 Python dictionaries are like magic spellbooks for programmers. They’re your go-to for managing data in key-value pairs — super handy for keeping things organized.
We took a tour of creating these wizards 🧙♂️, peeking into their secrets 🔍, changing spells on the fly ✨, and even erasing enchantments 🧹. Plus, we learned some nifty copy tricks to conjure new spellbooks 📚 without messing up the old ones.
With these tricks up your sleeve, you’ll be a dictionary wizard in no time! 🎩🔮
That’s a wrap for today’s dose of Python insights! 👋 Time to bid adieu, folks. Remember, code with joy and may your Python adventures be as smooth as a well-oiled machine! 🚀 Stay curious and keep coding! Bye for now! 👋👋