Dictionaries in Python
In Python, a dictionary is a collection of unordered and mutable key-value pairs. It is defined by enclosing a comma-separated sequence of key-value pairs within curly braces {}. Dictionaries do not allow duplicate keys, ensuring that each key is unique within the dictionary.
Here's an example of a dictionary called user with three key-value pairs:
user = {
"first_name":"Danny",
"last_name":"Brown",
"email":"danny@tutorialsbuddy.com"
}
Creating a Dictionary
In Python, you can create a dictionary by enclosing a comma-separated sequence of key-value pairs within curly braces {}. Each key-value pair consists of a key (which must be unique within the dictionary) and its associated value.
Example:
product = {
"name":"Laptop",
"code":1,
"brand":"Samsung",
"price": 1200.95,
"is_available": True
}
print(product)
Output:
{'name': 'Laptop', 'code': 1, 'brand': 'Samsung', 'price': 1200.95, 'is_available': True}
You can also create a dictionary using the dict() constructor.
Example:
product = dict(name = "Laptop", code = 1, brand = "Samsung", price = 1200.95, is_available = True)
print(product)
Output:
{'name': 'Laptop', 'code': 1, 'brand': 'Samsung', 'price': 1200.95, 'is_available': True}
Alternatively, you can create an empty dictionary and add key-value pairs later.
Example:
user = {} # Creating empty dictionary
# Adding key-value pairs later
user["first_name"] = "Danny"
user["last_name"] = "Xyz"
user["email"] = "danny@tutorialsbuddy.com"
print(user)
Output:
{'first_name': 'Danny', 'last_name': 'Xyz', 'email': 'danny@tutorialsbuddy.com'}
Accessing Dictionary Elements
In Python, you can access the value of a dictionary by referencing the key within square brackets.
Example:
product = {
"name":"Laptop",
"code":1,
"brand":"Samsung",
"price": 1200.95,
"is_available": True
}
print(product["name"])
print(product["code"])
print(product["brand"])
print(product["price"])
print(product["is_available"])
Output:
Laptop 1 Samsung 1200.95 True
In Python, you can also access a dictionary value by using the get() method, which takes a key and an optional default value as arguments and returns the associated value.
Example:
product = {
"name":"Laptop",
"code":1,
"brand":"Samsung",
"price": 1200.95,
"is_available": True
}
print(product.get("name"))
print(product.get("code"))
print(product.get("brand"))
print(product.get("price"))
print(product.get("is_available"))
print(product.get("color", "silver")) # get product color if exists else return default value silver
Output:
Laptop 1 Samsung 1200.95 True silver
Accessing Dictionary Values Using a Loop
In Python, you can access the values of a dictionary using the values() method to iterate over its values.
Example:
user = {
"first_name":"Danny",
"last_name":"Brown",
"email":"danny@tutorialsbuddy.com"
}
for v in user.values():
print(v)
Output:
Danny Brown danny@tutorialsbuddy.com
Accessing Dictionary Key-Value Pairs
In Python, you can access both the keys and values of a dictionary using the items() method to iterate over key-value pairs.
Example:
user = {
"first_name":"Danny",
"last_name":"Brown",
"email":"danny@tutorialsbuddy.com"
}
for key, value in user.items():
print(key + " : " +value)
Output:
first_name : Danny last_name : Brown email : danny@tutorialsbuddy.com
Accessing Dictionary Keys
In Python, you can access the keys simply by iterating through the dictionary.
Example:
user = {
"first_name":"Danny",
"last_name":"Brown",
"email":"danny@tutorialsbuddy.com"
}
for key in user:
print(key)
Output:
first_name last_name email
Adding New Key-Value Pair
In Python, you can add a key-value pair to a dictionary using the assignment operator (=) or the dict.update() method.
Example:
my_dict = {} # Create an empty dictionary
# Add key-value pairs to the dictionary using assignment operator
my_dict['key1'] = 'value1'
my_dict['key2'] = 'value2'
my_dict['key3'] = 'value3'
# You can also update the value of an existing key
my_dict['key1'] = 'new_value'
# Add key-value pairs to the dictionary using update method
my_dict.update({'key4': 'value4', 'key5': 'value5'})
print(my_dict)
Output:
{'key1': 'new_value', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4', 'key5': 'value5'}
Deleting Key-Value from a Dictionary
In Python, you can use the del keyword to delete a key from a dictionary.
Example:
user = {
"first_name":"Danny",
"last_name":"Brown",
"email":"danny@tutorialsbuddy.com"
}
del user["email"]
print(user)
Output:
{'first_name': 'Danny', 'last_name': 'Brown'}
Dictionary Length
In Python, the length of a dictionary can be obtained by using the len() function.
Example:
user = {
"first_name":"Danny",
"last_name":"Brown",
"email":"danny@tutorialsbuddy.com"
}
print(len(user))
Output:
3
Emptying a Dictionary
In Python, you can use the clear() method to empty or clear a dictionary.
Example:
user = {
"first_name":"Danny",
"last_name":"Brown",
"email":"danny@tutorialsbuddy.com"
}
# Emptying the dictionary using the clear() method
user.clear()
print(user)
Output:
{}
Copying a Dictionary
In Python, you can use the copy() method to copy one dictionary to another dictionary.
Example:
dict1 = {"name" : "Peter", "email" : "peter@tb.com", "customer_id" : "ABC123"}
dict2 = dict1.copy()
print(dict2)
Output:
{'name': 'Peter', 'email': 'peter@tb.com', 'customer_id': 'ABC123'}
Nested Dictionary
In Python, a nested Dictionary is a dictionary within a dictionary.
Example:
my_dict = {
"my_dict" : {
"key1" : "valu1",
"key2" : "value2",
"key3" : "value3"
,
"nested_dict" : {
"key4" : "key4",
"key5" : "key5",
"key6" : "key6"
}
}
}
print(my_dict)
Output:
{'my_dict': {'key1': 'valu1', 'key2': 'value2', 'key3': 'value3', 'nested_dict': {'key4': 'key4', 'key5': 'key5', 'key6': 'key6'}}}