Python Dictionary


In Python, a dictionary is one of the most versatile and powerful data structures. It allows you to store key-value pairs, enabling fast lookups, inserts, and updates. Unlike lists or tuples, dictionaries are unordered, which makes them perfect for situations where data needs to be associated with a specific key. In this blog, we will explore Python dictionaries, their features, and how to use them effectively with examples.

1. What is a Python Dictionary?

A dictionary in Python is an unordered collection of items. Each item in a dictionary is stored as a key-value pair, where the key is a unique identifier, and the value is the associated data. Dictionaries are mutable, meaning you can modify them after they are created.

1.1 Characteristics of a Dictionary

  • Unordered: The elements in a dictionary are unordered, meaning the key-value pairs do not have a specific index or order.
  • Mutable: You can change the contents of a dictionary by adding, modifying, or removing key-value pairs.
  • Key-Value Pairs: Each element in a dictionary is stored as a pair of keys and corresponding values.
  • Unique Keys: Keys in a dictionary must be unique. If you try to insert a duplicate key, the existing key's value will be updated.
  • Efficient Lookups: Dictionaries provide fast lookups, allowing you to retrieve values based on their keys.

2. Creating a Dictionary

A Python dictionary is created using curly braces {} with key-value pairs, where the key and value are separated by a colon :.

2.1 Basic Dictionary Creation

Example:

my_dict = {"name": "John", "age": 30, "city": "New York"}
print(my_dict)
# Output: {'name': 'John', 'age': 30, 'city': 'New York'}

2.2 Creating a Dictionary with the dict() Constructor

You can also create a dictionary using the dict() constructor, where the keys are specified as strings, and values are passed as arguments.

Example:

my_dict = dict(name="John", age=30, city="New York")
print(my_dict)
# Output: {'name': 'John', 'age': 30, 'city': 'New York'}

2.3 Creating an Empty Dictionary

An empty dictionary can be created by using curly braces {} or the dict() constructor.

Example:

empty_dict = {}
# or
empty_dict2 = dict()
print(empty_dict)  # Output: {}

3. Accessing Dictionary Elements

To access elements in a dictionary, you use the key. Since dictionaries are unordered, you cannot access elements using an index.

3.1 Accessing Values by Key

Example:

my_dict = {"name": "John", "age": 30, "city": "New York"}
print(my_dict["name"])  # Output: John

3.2 Using get() Method

You can also use the get() method, which returns None (or a default value if specified) if the key does not exist, avoiding a KeyError.

Example:

print(my_dict.get("age"))  # Output: 30
print(my_dict.get("country", "Not Found"))  # Output: Not Found

4. Modifying a Dictionary

Dictionaries are mutable, meaning you can add, update, and remove key-value pairs after the dictionary is created.

4.1 Adding or Updating Key-Value Pairs

To add or update a key-value pair, simply assign a value to a specific key.

Example:

my_dict = {"name": "John", "age": 30}
# Adding a new key-value pair
my_dict["city"] = "New York"
print(my_dict)
# Output: {'name': 'John', 'age': 30, 'city': 'New York'}

# Updating an existing key-value pair
my_dict["age"] = 31
print(my_dict)
# Output: {'name': 'John', 'age': 31, 'city': 'New York'}

4.2 Removing Key-Value Pairs

You can remove items from a dictionary using several methods:

  • pop(): Removes a key-value pair by key and returns the value.
  • popitem(): Removes and returns the last inserted key-value pair.
  • del: Removes a key-value pair by key.
  • clear(): Removes all key-value pairs from the dictionary.

Example:

# Using pop() method
my_dict = {"name": "John", "age": 30, "city": "New York"}
removed_value = my_dict.pop("age")
print(removed_value)  # Output: 30
print(my_dict)  # Output: {'name': 'John', 'city': 'New York'}

# Using popitem() method
removed_item = my_dict.popitem()
print(removed_item)  # Output: ('city', 'New York')
print(my_dict)  # Output: {'name': 'John'}

# Using del keyword
del my_dict["name"]
print(my_dict)  # Output: {}

# Using clear() method
my_dict.clear()
print(my_dict)  # Output: {}

5. Dictionary Methods

Python dictionaries come with several useful built-in methods to manipulate and interact with the data.

5.1 keys() Method

The keys() method returns a view object that displays all the keys in the dictionary.

Example:

my_dict = {"name": "John", "age": 30, "city": "New York"}
keys = my_dict.keys()
print(keys)  # Output: dict_keys(['name', 'age', 'city'])

5.2 values() Method

The values() method returns a view object that displays all the values in the dictionary.

Example:

values = my_dict.values()
print(values)  # Output: dict_values(['John', 30, 'New York'])

5.3 items() Method

The items() method returns a view object that displays all the key-value pairs in the dictionary.

Example:

items = my_dict.items()
print(items)  # Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])

5.4 update() Method

The update() method allows you to update a dictionary with another dictionary or an iterable of key-value pairs.

Example:

my_dict = {"name": "John", "age": 30}
new_data = {"city": "New York", "age": 31}
my_dict.update(new_data)
print(my_dict)  # Output: {'name': 'John', 'age': 31, 'city': 'New York'}

5.5 copy() Method

The copy() method creates a shallow copy of the dictionary.

Example:

my_dict = {"name": "John", "age": 30}
copied_dict = my_dict.copy()
print(copied_dict)  # Output: {'name': 'John', 'age': 30}

6. Nested Dictionaries

Dictionaries can contain other dictionaries, which are referred to as nested dictionaries. This allows for hierarchical data structures.

6.1 Accessing Nested Dictionary Elements

Example:

my_dict = {
    "name": "John",
    "age": 30,
    "address": {"street": "123 Main St", "city": "New York"}
}

# Accessing elements in the nested dictionary
print(my_dict["address"]["city"])  # Output: New York

7. Dictionary Comprehensions

Similar to list comprehensions, Python also supports dictionary comprehensions, allowing you to create dictionaries in a concise way.

Example:

# Create a dictionary with squares of numbers
squares = {x: x**2 for x in range(5)}
print(squares)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

8. When to Use a Dictionary?

Dictionaries are ideal in the following situations:

  • When you need to store data with unique keys, such as a phonebook where names are keys and phone numbers are values.
  • When you need to quickly access data via a key, rather than using an index.
  • When you need to store data where each key maps to a unique value, such as counting occurrences of items.

9. Dictionary vs. List: Key Differences

Although dictionaries and lists share some similarities, they are designed for different purposes. Here are some key differences:

Feature Dictionary List
Data Structure Key-value pairs Ordered collection of items
Accessing Elements By key By index
Order Unordered (before Python 3.7) Ordered
Mutability Mutable Mutable
Duplicates No duplicate keys allowed Duplicates allowed