What is Python Dictionaries

In Python, a dictionary is a built-in data type that allows you to store data in key-value pairs. Each key in a dictionary is unique and maps to a corresponding value, enabling efficient data retrieval and manipulation. Dictionaries are mutable, meaning you can modify their content after creation, and they maintain the order of items as of Python version 3.7.

Key Characteristics of Python Dictionaries

  • Key-Value Pairs: Dictionaries consist of unique keys mapped to values.
  • Mutable: You can add, remove, or modify items within a dictionary.
  • Ordered: As of Python 3.7, dictionaries maintain the insertion order of items.
  • Keys Must Be Immutable: Keys can be data types like strings, numbers, or tuples, but not lists or other dictionaries.

Creating a Dictionary

You can create a dictionary using curly braces {} with key-value pairs separated by colons, or by using the dict() constructor.

# Using curly braces
person = {
    "name": "Dharmender",
    "age": 30,
    "city": "Bangalore"
}

# Using the dict() constructor
person = dict(name="Dharmender", age=30, city="Bangalore")

Accessing and Modifying Values

Access values by referencing their keys, and modify them by assigning new values to existing keys.

# Accessing a value
print(person["name"])  # Output: Dharmender

# Modifying a value
person["age"] = 31
print(person["age"])  # Output: 31

Adding and Removing Items

Add new key-value pairs by assigning a value to a new key, and remove items using the del statement or the pop() method.

# Adding a new key-value pair
person["email"] = "dharmender@blogshub.com"
print(person)
# Output: {'name': 'Dharmender', 'age': 31, 'city': 'Bangalore', 'email': 'dharmender@blogshub.com'}

# Removing a key-value pair using del
del person["city"]
print(person)
# Output: {'name': 'Dharmender', 'age': 31, 'email': 'dharmender@blogshub.com'}

# Removing a key-value pair using pop()
email = person.pop("email")
print(email)   # Output: dharmender@blogshub.com
print(person)  # Output: {'name': 'Dharmender', 'age': 31}

Dictionary Methods

Python dictionaries come with several built-in methods to facilitate operations:

  • keys(): Returns a view object of all keys.
  • values(): Returns a view object of all values.
  • items(): Returns a view object of all key-value pairs.
  • get(key, default): Returns the value for a key if it exists; otherwise, returns the default value.
  • update([other]): Updates the dictionary with key-value pairs from another dictionary or iterable.
# Using dictionary methods
print(person.keys())    # Output: dict_keys(['name', 'age'])
print(person.values())  # Output: dict_values(['Dharmender', 31])
print(person.items())   # Output: dict_items([('name', 'Dharmender'), ('age', 31)])

# Using get() method
print(person.get("name"))        # Output: Dharmender
print(person.get("address", "Not Available"))  # Output: Not Available

# Using update() method
person.update({"age": 32, "city": "Delhi"})
print(person)
# Output: {'name': 'Dharmender', 'age': 32, 'city': 'Delhi'}

Practical Applications of Dictionaries

Dictionaries are versatile and widely used in various scenarios:

  • Configuration Settings: Store and manage configuration parameters.
  • Counting Occurrences: Count the frequency of items in a dataset.
  • Representing JSON Data: Work with JSON data, which maps directly to Python dictionaries.
  • Database Records: Store and manipulate records retrieved from databases.

Understanding and effectively utilizing Python dictionaries can significantly enhance your ability to write efficient and readable code, especially when managing complex data structures.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *