Python dictionary is a collection of key-value pairs
, where each key is unique and associated with a value. Dictionaries are mutable, meaning they can be changed after they are created.
Syntax
A dictionary in Python is defined using curly braces {}
and contains key-value pairs separated by a colon :
. Each key-value pair is separated by commas.
dictionary_name = {key1: value1, key2: value2, ...}
Create a Dictionary
To create a dictionary, you can use the curly braces {}
and separate the key-value pairs with colons :
.
person = {"name": "John", "age": 30, "city": "New York"} print(person) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
or
# Creating an empty dictionary empty_dict = {} # Adding key-value pairs to the dictionary empty_dict["name"] = "Alice" empty_dict["age"] = 30 empty_dict["city"] = "New York" # Accessing and printing the dictionary print(empty_dict)
You also can use dict()
method to create a dictionary.
Example:
# Creating a dictionary using dict() constructor with key-value pairs dict_constr_1 = dict(name="Bob", age=25, city="San Francisco") # Creating a dictionary using dict() constructor with a list of tuples dict_constr_2 = dict([("key1", "value1"), ("key2", "value2"), ("key3", "value3")]) # Accessing and printing the dictionaries print(dict_constr_1) print(dict_constr_2)
Output:
{'name': 'Bob', 'age': 25, 'city': 'San Francisco'} {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
Accessing and Updating Values
You can access values in a dictionary using keys and update them as needed.
# Accessing and updating values print(my_dict["name"]) # Output: Alice my_dict["age"] = 31
Add a Key-Value Pair
To add a new key-value pair to a dictionary, you can use the assignment operator =
to assign a value to a new key.
person = {"name": "John", "age": 30, "city": "New York"} person["country"] = "USA" print(person) # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
Remove a Key-Value Pair
Here are two methods to remove a key-value pair in a dictionary.
del
person = {"name": "John", "age": 30, "city": "New York"} del person["city"] print(person) # Output: {'name': 'John', 'age': 30}
pop()
person = {"name": "John", "age": 30, "city": "New York"} city = person.pop("city") print(person) # Output: {'name': 'John', 'age': 30} print(city) # Output: New York
Iterate over a Dictionary
To iterate over a dictionary, you can use a for loop
.
Example:
person = {"name": "John", "age": 30, "city": "New York"} for key in person: print(key, person[key])
Output:
name John age 30 city New York
Alternatively, you can use the items()
method to iterate over both the keys and values.
Example:
person = {"name": "John", "age": 30, "city": "New York"} for key, value in person.items(): print(key, value)
Output:
name John age 30 city New York
Dictionary Operations
Here are some common dictionary operations:
Get a value
Use the get()
method to retrieve a value by its key.
person = {"name": "John", "age": 30, "city": "New York"} print(person.get("name")) # Output: John
Check if a key exists
Use the in operator to check if a key exists in the dictionary.
person = {"name": "John", "age": 30, "city": "New York"} print("name" in person) # Output: True print("email" in person) # Output: False
Get all keys
Use the keys()
method to get all the keys in the dictionary.
person = {"name": "John", "age": 30, "city": "New York"} print(person.keys()) # Output: dict_keys(['name', 'age', 'city'])
Get all values
Use the values()
method to get all the values in the dictionary.
person = {"name": "John", "age": 30, "city": "New York"} print(person.values()) # Output: dict_values(['John', 30, 'New York'])
Get all items
Use the items()
method to get all the key-value pairs in the dictionary.
person = {"name": "John", "age": 30, "city": "New York"} print(person.items()) # Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
Clear a dictionary
Use the clear()
method to remove all key-value pairs from the dictionary.
person = {"name": "John", "age": 30, "city": "New York"} person.clear() print(person) # Output: {}
Copy a dictionary
Use the copy()
method to create a copy of the dictionary.
person = {"name": "John", "age": 30, "city": "New York"} person_copy = person.copy() print(person_copy) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
Merge two dictionaries:
Use the update()
method to merge two dictionaries.
person1 = {"name": "John", "age": 30} person2 = {"city": "New York", "country": "USA"} person1.update(person2) print(person1) # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}