Python Dictionaries

A dictionary in Python is an unordered, mutable collection of key-value pairs. Each key in a dictionary must be unique and immutable (like strings, numbers, or tuples), while the values can be of any data type.

Creating a Dictionary

You can create a dictionary using curly braces {} or the dict() constructor.

# Creating dictionaries
empty_dict = {}  # An empty dictionary
person = {"name": "John", "age": 25, "profession": "Engineer"}

print(person)  # Output: {'name': 'John', 'age': 25, 'profession': 'Engineer'}

Try It Now

Accessing Dictionary Elements

You can access dictionary values using their keys.

# Accessing values
person = {"name": "John", "age": 25, "profession": "Engineer"}

print(person["name"])  # Output: John
print(person["age"])   # Output: 25

Try It Now

Note: If you try to access a key that doesn’t exist, Python raises a KeyError.

Adding and Updating Elements

To add or update elements in a dictionary, use the key and assign a new value.

# Adding and updating elements
person = {"name": "John", "age": 25}

# Adding a new key-value pair
person["city"] = "New York"

# Updating an existing value
person["age"] = 26

print(person)  # Output: {'name': 'John', 'age': 26, 'city': 'New York'}

Try It Now

Removing Elements

Python provides several methods to remove elements from a dictionary.

  • pop(key): Removes the element with the specified key and returns its value.
  • popitem(): Removes and returns the last inserted key-value pair (Python 3.7+).
  • del: Deletes a key-value pair by key.
  • clear(): Removes all elements from the dictionary.
# Removing elements
person = {"name": "John", "age": 25, "city": "New York"}

# Using pop()
age = person.pop("age")
print(age)  # Output: 25

# Using del
del person["city"]

# Using clear()
person.clear()

print(person)  # Output: {}

Try It Now

Common Dictionary Methods

Here are some of the most useful dictionary methods:

  • get(key[, default]): Returns the value for the specified key. If the key doesn’t exist, it returns the default value (or None).
  • keys(): Returns a view object containing the keys of the dictionary.
  • values(): Returns a view object containing the values of the dictionary.
  • items(): Returns a view object containing the key-value pairs of the dictionary.
  • update([other]): Updates the dictionary with key-value pairs from another dictionary or an iterable of key-value pairs.

Examples:

# Dictionary methods
person = {"name": "John", "age": 25}

# get() method
print(person.get("name"))  # Output: John
print(person.get("city", "Not found"))  # Output: Not found

# keys(), values(), and items() methods
print(person.keys())    # Output: dict_keys(['name', 'age'])
print(person.values())  # Output: dict_values(['John', 25])
print(person.items())   # Output: dict_items([('name', 'John'), ('age', 25)])

Try It Now

Dictionary Comprehension

You can create dictionaries using dictionary comprehension for concise and readable code.

# Dictionary comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Try It Now

Nesting Dictionaries

Dictionaries can contain other dictionaries, allowing you to create nested data structures.

# Nested dictionary
students = {
    "John": {"age": 25, "grade": "A"},
    "Jane": {"age": 22, "grade": "B"}
}

print(students["John"]["grade"])  # Output: A

Try It Now

Conclusion

Python dictionaries are a powerful and flexible way to store key-value pairs. With various methods and operations, you can easily manipulate and access data efficiently. Understanding dictionaries will help you solve complex problems and organize data more effectively.