fbpx

Dictionaries in Python

A dictionary is a versatile and mutable data structure that stores data in key-value pairs. Dictionaries are defined using curly braces {} and consist of keys and their corresponding values.

1. Basic Syntax:

# Example of a dictionary
person = {"name": "Alice", "age": 30, "city": "Wonderland"}

2. Accessing Values:

Values in a dictionary are accessed using their keys.

# Accessing values
name = person["name"]
age = person["age"]

3. Adding and Updating Values:

You can add new key-value pairs or update existing values in a dictionary.

# Adding a new key-value pair
person["gender"] = "Female"

# Updating the value of an existing key
person["age"] = 31

4. Removing Key-Value Pairs:

You can use the del statement to remove a key-value pair.

# Removing a key-value pair
del person["city"]

5. Common Operations on Dictionaries:

  • Checking if a Key Exists:
  if "name" in person:
      print("Name is present.")
  • Getting All Keys and Values:
  keys = person.keys()
  values = person.values()
  • Iterating Through Keys and Values:
  for key, value in person.items():
      print(f"{key}: {value}")

6. Nested Dictionaries:

Dictionaries can be nested, allowing you to create more complex data structures.

# Example of a nested dictionary
company = {
    "name": "TechCorp",
    "employees": [
        {"name": "Alice", "position": "Engineer"},
        {"name": "Bob", "position": "Designer"},
    ]
}

7. Choosing Keys:

  • Keys in a dictionary must be unique.
  • Keys are typically strings or numbers, but they can be of any immutable data type.
  • Avoid using mutable types like lists as keys.

8. Use Cases:

  • Storing Configuration Settings:
  settings = {"theme": "dark", "font_size": 14}
  • Representing Entities:
  person = {"name": "Alice", "age": 30, "city": "Wonderland"}
  • Counting Occurrences:
  word_count = {"apple": 3, "orange": 5, "banana": 2}

9. Conclusion:

Dictionaries are powerful data structures in Python, offering efficient key-based access to values. They are widely used for a variety of purposes, including representing entities, storing configurations, and counting occurrences.

In the next sections, we’ll explore more advanced topics and practical applications of data structures in Python.