Python dictionaries

Dictionaries in Python are versatile data structures that store collections of key-value pairs. Each key is associated with a value, and you can use keys to efficiently retrieve corresponding values. Dictionaries are often used when you need to store and access data with a specific label or identifier. Here's an exploration of dictionaries, their syntax, and their usage:

Dictionaries are defined using curly braces "{}". Each key-value pair is separated by a colon ":". Keys must be unique and are usually strings or numbers, while values can be of any data type.

# Creating a dictionary
person = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

You can access values in a dictionary using their keys within square brackets "[]".

name = person['name']
print(name)  # Output: 'John'

You can add new key-value pairs to a dictionary or modify existing values using the assignment operator.

# Adding a new key-value pair
person['occupation'] = 'Engineer'

# Modifying an existing value
person['age'] = 31

Dictionaries have several useful methods for working with their data:

  • keys(): Returns a list of all keys.
  • values(): Returns a list of all values.
  • items(): Returns a list of key-value pairs as tuples.
  • get(key): Retrieves the value for a given key. Returns `None` if key not found.
  • pop(key): Removes and returns the value associated with a key.
  • update(dictionary): Merges the content of another dictionary into the current one.

You can iterate through the keys, values, or items (key-value pairs) of a dictionary using loops.

# Iterating through keys
for key in person:
    print(key)

# Iterating through values
for value in person.values():
    print(value)

# Iterating through key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")

Dictionaries are useful for various scenarios:

  • Storing Configuration Settings: You can use keys to represent configuration options and values to store their settings.
  • Data Mapping: Dictionaries are often used to map unique identifiers (keys) to corresponding data (values).
  • Counting Occurrences: You can use keys to represent items and values to store their occurrence counts.
  • Caching: Dictionaries are useful for storing computed results to avoid redundant calculations.
  • Representing Real-World Objects: You can use dictionaries to represent attributes of real-world objects, like people, products, or locations.
  • JSON-Like Data: Dictionaries are similar to JSON (JavaScript Object Notation) data, which is widely used for data interchange.

Dictionaries are versatile and powerful tools for managing data in Python. They provide an efficient way to store, access, and manipulate key-value pairs, making them essential for various programming tasks.