Dictionaries are defined by placing a comma-separated sequence of key-value pairs inside curly braces {}
.
my_dict = {"key1": "value1", "key2": "value2"}
# Empty dictionary
empty_dict = {}
# Dictionary with integer keys
int_keys_dict = {1: "one", 2: "two", 3: "three"}
# Dictionary with string keys
str_keys_dict = {"name": "Alice", "age": 30, "city": "New York"}
# Mixed keys dictionary
mixed_keys_dict = {1: "one", "two": 2, 3.0: [1, 2, 3]}
# Using the dict() function
dict_func = dict(name="Alice", age=30, city="New York")
#From a List of Tuples:
list_of_tuples = [("name", "Charlie"), ("age", 35), ("city", "Chicago")]
dict_from_tuples = dict(list_of_tuples)
get()
method to avoid KeyError
if the key is not found.xxxxxxxxxx
person = {"name": "Alice", "age": 30, "city": "New York"}
print(person["name"]) # Output: Alice
print(person["age"]) # Output: 30
print(my_dict.get("name")) # Output: Alice
print(my_dict.get("country", "Unknown")) # Output: Unknown
You can add new key-value pairs or modify existing ones.
xxxxxxxxxx
person = {"name": "Alice", "age": 30}
# Adding a new key-value pair
person["city"] = "New York"
print(person) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
# Modifying an existing value
person["age"] = 31
print(person) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York'}
You can remove elements using del
, pop()
, popitem()
, and clear()
.
xxxxxxxxxx
person = {"name": "Alice", "age": 30, "city": "New York"}
# Using del
del person["city"]
print(person) # Output: {'name': 'Alice', 'age': 30}
# Using pop()
age = person.pop("age")
print(age) # Output: 30
print(person) # Output: {'name': 'Alice'}
# Using popitem()
name = person.popitem()
print(name) # Output: ('name', 'Alice')
print(person) # Output: {}
# Using clear()
person = {"name": "Alice", "age": 30, "city": "New York"}
person.clear()
print(person) # Output: {}
Dictionaries have many built-in methods for various operations. Here are some of the most commonly used ones:
keys() | Returns a view object containing the dictionary's keys.
|
values() | Returns a view object of the dictionary's values.
|
items() | Returns a view object containing the dictionary's key-value pairs.
|
get() | Returns the value for a specified key if the key is in the dictionary; otherwise, it returns a default value.
|
update() | Updates the dictionary with elements from another dictionary or an iterable of key-value pairs.
|
pop() | Removes the specified key and returns its value. If the key is not found, it returns a default value if provided.
|
popitem() | Removes and returns the last key-value pair inserted into the dictionary.
|
setdefault() | Returns the value of a specified key. If the key does not exist, it inserts the key with a specified value.
|
xxxxxxxxxx
# Creating dictionaries
person = {"name": "Alice", "age": 30, "city": "New York"}
print(person) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
# Accessing elements
print(person["name"]) # Output: Alice
print(person.get("age")) # Output: 30
# Adding and modifying elements
person["email"] = "alice@example.com"
person["age"] = 31
print(person) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'email': 'alice@example.com'}
# Removing elements
person.pop("city")
print(person) # Output: {'name': 'Alice', 'age': 31, 'email': 'alice@example.com'}
# Dictionary methods
print(person.keys()) # Output: dict_keys(['name', 'age', 'email'])
print(person.values()) # Output: dict_values(['Alice', 31, 'alice@example.com'])
print(person.items()) # Output: dict_items([('name', 'Alice'), ('age', 31), ('email', 'alice@example.com')])
# Updating the dictionary
person.update({"city": "New York", "phone": "123-456-7890"})
print(person) # Output: {'name': 'Alice', 'age': 31, 'email': 'alice@example.com', 'city': 'New York', 'phone': '123-456-7890'}
# Dictionary comprehension
squares = {x: x*x for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Dictionary Comprehension
You can create dictionaries using dictionary comprehensions, which are similar to list comprehensions.
squares = {x: x*x for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Checking Key Existence
You can check if a key exists in a dictionary using the in
keyword.
print("name" in person) # Output: True
print("address" in person) # Output: False