A dictionary in Python is mutable and an unordered collection in the form of key-value pairs, where each key must be unique. Dictionaries are defined within curly braces {}
and use a colon :
to separate keys from values. They are optimized for retrieving a value when the key is known.
Basic Syntax
my_dict = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3'
}
Key Characteristics of Dictionaries
- Unordered: The items in a dictionary do not have an order.
- Mutable: You can change dictionaries in place, by adding, modifying, or deleting key-value pairs.
- Indexed by keys: Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys.
- Key Uniqueness: In a dictionary, each key must be unique.
A dictionary in Python is an unordered collection of data in the form of key:value pair . Here’s a simple dictionary with some basic operations:
my_dict = {'site': 'PythonCorner', 'age': 30, 'city': 'Pune'}
1. Accessing Values
You can access the value for a given key using the key itself.
print(my_dict['site']) # Output: PythonCorner
Or use the get
method, which allows you to provide a default value.
print(my_dict.get('country', 'USA')) # Output: USA
2. Modifying Dictionary
- Adding/Updating Entries
my_dict['country'] = 'USA' # Add a new key:value pair
my_dict['name'] = 'Doe' # Update the value for the key 'name'
- Deleting Entries
del my_dict['age'] # Removes the entry with key 'age'
- Merging Dictionaries
extra_info = {'state': 'NY', 'zip': '10001'}
my_dict.update(extra_info)
3. Keys, Values, and Items
print(my_dict.keys()) # Output: dict_keys(['name', 'city', 'country', 'state', 'zip'])
print(my_dict.values()) # Output: dict_values(['Doe', 'New York', 'USA', 'NY', '10001'])
print(my_dict.items()) # Output: dict_items([('name', 'Doe'), ('city', 'New York'), ('country', 'USA'), ('state', 'NY'), ('zip', '10001')])
4. Iterating Through a Dictionary
for key, value in my_dict.items():
print(f"{key}: {value}")
5. Dictionary Comprehension
Just like list comprehensions, Python allows dictionary comprehensions.
squares = {x: x*x for x in range(6)} # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
6. Nested Dictionaries
A dictionary can contain another dictionary called Nested dictionaries, which in turn can contain dictionaries themselves, and so on to arbitrary depth. This is known as nested dictionary.
users = {
'user1': {
'name': 'John',
'age': 30,
},
'user2': {
'name': 'Marie',
'age': 22,
}
}
7. Using defaultdict
A defaultdict
automatically handles missing keys and calls a factory function to supply their default values.
from collections import defaultdict
count = defaultdict(int)
names_list = "Python Corner Python Corner Python PythonCorner".split()
for names in names_list:
count[names] += 1
# Output: defaultdict(<class 'int'>, {'Python': 3, 'Corner': 2, 'PythonCorner': 1})
8. Using Counter
A Counter is a dict subclass for counting hashable objects.
from collections import Counter
count = Counter("Dog Cat Dog Cat Dog Horse Sheep Dog".split())
# Output: Counter({'Dog': 4, 'Cat': 2, 'Horse': 1,'Sheep':1})
Example: Simple Phone Book
phone_book = {
'John': '555-555-5555',
'Alice': '555-555-5556',
'Bob': '555-555-5557'
}
name = 'Alice'
number = phone_book.get(name)
if number:
print(f"{name}'s phone number is {number}")
else:
print(f"{name} is not in the phone book.")
Conclusion
Dictionaries in Python provide a wide range of operations and methods to work with key:value pairs, providing fast lookups, dynamic resizing, and efficient memory usage. Understanding the underlying mechanisms, such as hashing and comparison, of dictionaries gives you the power to utilize them effectively in your code.Dictionaries are highly versatile and are used in various forms across Python programs to handle data efficiently. They allow you to quickly retrieve, update, or delete items without having to search through your dataset linearly. This is due to the way they are implemented in Python, using a data structure called a hashtable that allows almost O(1) time complexity for lookup, insertion, and deletion operations