In Python, a dictionary is a mutable and dynamic data structure used to store a collection of key-value pairs. Dictionaries are denoted by enclosing comma-separated key-value pairs in curly braces '{}'. Each key is separated from its value by a colon ':'.
Key properties of Python dictionaries are:
1. Key-Value Pairs: Each item in a dictionary is a pair of a unique key and a value associated with that key. You can access the value by referring to its key.
2. Ordered: Dictionaries in Python are now ordered collections. Since Python 3.7, the insertion order of items is maintained, meaning items are returned in the order they were added to the dictionary.
3. Allows Duplicate Values: While keys in a dictionary must be unique, values can be duplicated. Duplicate values will overwrite existing values.
4. Mutable: Dictionaries in Python are mutable, which means their elements (key-value pairs) can be modified after creation.
Creating Dictionaries:
To create a dictionary in Python, you simply enclose the key-value pairs you want to include within curly braces '{}', separated by commas.
# Example of creating dictionaries
personal_info = {"name": "Alice", "age": 25, "city": "New York"}
grades = {"Math": "A", "Physics": "B", "History": "A"}
mixed = {1: "Alice", "two": [1, 2, 3], (3, 4): "tuple key"}
empty_dict = {} # An empty dictionary
Using dict() Constructor:
You can also create a dictionary in Python using the 'dict()' constructor.
newdict = dict(name = "Alice", age = 25, country = "England")
print(newdict) # Outputs: {'name': 'Alice', 'age': 25, 'country': 'England'}
In this case, the arguments to 'dict()' are a series of keyword arguments where the argument names are treated as the dictionary keys and the argument values are the dictionary values.
You can also create a dictionary from an existing iterable object such as a list of tuples, where each tuple is a key-value pair.
# Using dict() constructor
grades = dict([("Math", "A"), ("Physics", "B"), ("History", "A")])
print(grades) # Outputs: {'Math': 'A', 'Physics': 'B', 'History': 'A'}
Dictionary Length:
In Python, the `len()` function is used to get the number of items (key-value-pairs) in a dictionary.
Here is an example:
personal_info = {"name": "Alice", "age": 25, "city": "New York", "job": "Engineer"}
length = len(personal_info)
print(length) # Outputs: 4
Access Items:
In Python, you can access items in a dictionary in various ways:
1. Access by Key (Square Brackets): You can access an item in a dictionary by referring to its key inside square brackets `[]`. If the key does not exist, Python raises a `KeyError`.
personal_info = { "name": "Alice", "age" : 25, "city" : "New York" }
print(personal_info["name"]) # Outputs: 'Alice'
2. Access by Key (`get()` method): Alternatively, you can use the `get()` method, which returns the value for a key if it exists in the dictionary. If the key does not exist, it returns `None`, unless a default value is provided.
print(personal_info.get("name")) # Outputs : 'Alice'
print(personal_info.get("job")) # Outputs : None
3. Access All Keys (`keys()` method): The `keys()` method returns a view object that contains the keys of the dictionary.
keys = personal_info.keys()
print(keys) # Outputs: dict_keys(['name', 'age', 'city'])
4. Access All Values (`values()` method): The `values()` method returns a view object that contains the values of the dictionary.
values = personal_info.values()
print(values) # Outputs: dict_values(['Alice', 25, 'New York'])
5. Access All Key-Value Pairs (`items()` method): The `items()` method returns a view object that contains the key-value pairs of the dictionary.
items = personal_info.items()
print(items) # Outputs: dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])
Check Items:
personal_info = {"name": "Alice", "age": 25, "city": "New York"}
# Check if a key exists
if "name" in personal_info:
print("Yes, 'name' is one of the keys in the personal_info dictionary") # This will be printed
if "job" in personal_info:
print("Yes, 'job' is one of the keys in the personal_info dictionary") # This will not be printed
# Check if a value exists
if "Alice" in personal_info.values() :
print("Yes, 'Alice' is one of the values in the personal_info dictionary") # This will be printed
if "Engineer" in personal_info.values() :
print("Yes, 'Engineer' is one of the values in the personal_info dictionary") # This will not be printed
Modify Items:
personal_info = {"name": "Alice", "age": 25, "city": "New York"}
# Change an existing item
personal_info["city"] = "Boston"
print(personal_info) # Outputs: {'name': 'Alice', 'age': 25, 'city': 'Boston'}
# Updating an existing dictionary
personal_info = {"name": "Alice", "age": 25, "city": "New York"}
additional_info = {"city": "Boston", "job": "Engineer"}
personal_info.update(additional_info)
print(personal_info)
# Outputs: {'name': 'Alice', 'age': 25, 'city': 'Boston', 'job': 'Engineer'}
Add Items:
personal_info = { "name": "Alice", "age" : 25, "city" : "New York" }
# Add a new item
personal_info["job"] = "Engineer"
print(personal_info) # Outputs: {'name': 'Alice', 'age' : 25, 'city' : 'New York', 'job' : 'Engineer'}
Copy Dictionary:
original_dict = {"key1": "value1", "key2": "value2"}
# Create a copy of the dictionary
copy_dict = original_dict.copy()
print(copy_dict) # Output: {'key1': 'value1', 'key2': 'value2'}
import copy
original_dict = {"key1": ["value1", "value2"], "key2": {"inner_key": "value"}}
# Create a deep copy of the dictionary
deep_copy_dict = copy.deepcopy(original_dict)
# Now, if you modify a mutable value in the original dictionary, it won't affect the copied dictionary.
original_dict["key1"].append("value3")
print(original_dict) # Output: {'key1': ['value1', 'value2', 'value3'], 'key2': {'inner_key': 'value'}}
print(deep_copy_dict) # Output: {'key1': ['value1', 'value2'], 'key2': {'inner_key': 'value'}}
Remove Items:
dict1 = {"name": "Alice", "age": 25}
age = dict1.pop("age")
print(age) # Output: 25
print(dict1) # Output: {'name': 'Alice'}
dict1 = {"name": "Alice", "age": 25}
item = dict1.popitem()
print(item) # Output: ('age', 25)
print(dict1) # Output: {'name': 'Alice'}
dict1 = {"name": "Alice", "age": 25}
dict1.clear()
print(dict1) # Output: {}
dict1 = {"name": "Alice", "age": 25}
del dict1["name"]
print(dict1) # Output: {'age': 25}
dict1 = {"name": "Alice", "age": 25}
del dict1
print(dict1) # This will raise a NameError because dict1 no longer exists