Dictionaries in Python

Characteristics:

  1. Mutable: Dictionaries can be modified after their creation. You can add, remove, or change items.
  2. Unordered (Python < 3.7): Prior to Python 3.7, dictionaries did not maintain the order of elements.
  3. Ordered (Python >= 3.7): Starting with Python 3.7, dictionaries maintain the order of items based on the order of insertion.
  4. Key-Value Pairs: Dictionaries consist of key-value pairs, where keys are unique and used to access corresponding values.
  5. Heterogeneous: Both keys and values can be of any data type, and different key-value pairs can have different types.

Syntax:

Dictionaries are defined by placing a comma-separated sequence of key-value pairs inside curly braces {}.

my_dict = {"key1": "value1", "key2": "value2"}

Advantages of Dictionaries

  • Fast Lookup: Dictionaries provide fast lookups for keys, making them ideal for scenarios where quick access to data is required.
  • Flexible Data Storage: Dictionaries can store a variety of data types as keys and values, offering great flexibility.
  • Readable Code: Using meaningful keys makes code more readable and self-documenting.

Use Cases for Dictionaries

  • Storing Configuration Settings: Dictionaries are commonly used to store configuration settings.
  • Implementing Caches: Due to their fast lookup capabilities, dictionaries are often used to implement caches.
  • Counting Occurrences: Dictionaries can be used to count occurrences of items in a collection.
  • Associating Data: Dictionaries are perfect for associating pairs of data, like names and ages, words and definitions, etc.
Creating Dictionaries:
Accessing Elements:
  • Elements in a dictionary can be accessed using keys.
  • You can also use the get() method to avoid KeyError if the key is not found.
Adding and Updating Elements:

You can add new key-value pairs or modify existing ones.

Removing Elements

You can remove elements using del, pop(), popitem(), and clear().


Dictionary Methods

Dictionaries have many built-in methods for various operations. Here are some of the most commonly used ones:

keys()

Returns a view object containing the dictionary's keys.

person = {"name": "Alice", "age": 30}
keys = person.keys()
print(keys)  # Output: dict_keys(['name', 'age'])
values()

Returns a view object of the dictionary's values.

values = person.values()
print(values)  # Output: dict_values(['Alice', 30])
items()

Returns a view object containing the dictionary's key-value pairs.

items = person.items()
print(items)  # Output: dict_items([('name', 'Alice'), ('age', 30)])

get()

Returns the value for a specified key if the key is in the dictionary; otherwise, it returns a default value.

age = person.get("age", "Not Available")
print(age)  # Output: 30

city = person.get("city", "Not Available")
print(city)  # Output: Not Available
update()

Updates the dictionary with elements from another dictionary or an iterable of key-value pairs.

person.update({"city": "New York", "email": "alice@example.com"})
print(person)  # Output: {'name': 'Alice', 'age': 30, 'city': 'New York', 'email': 'alice@example.com'}
pop()

Removes the specified key and returns its value. If the key is not found, it returns a default value if provided.

city = person.pop("city", "Not Found")
print(city)  # Output: New York
print(person)  # Output: {'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}
popitem()

Removes and returns the last key-value pair inserted into the dictionary.

last_item = person.popitem()
print(last_item)  # Output: ('email', 'alice@example.com')
print(person)  # Output: {'name': 'Alice', 'age': 30}
setdefault()

Returns the value of a specified key. If the key does not exist, it inserts the key with a specified value.

email = person.setdefault("email", "default@example.com")
print(email)  # Output: default@example.com
print(person)  # Output: {'name': 'Alice', 'age': 30, 'email': 'default@example.com'}
Code Example

Dictionary Operations

  1. Dictionary Comprehension

    You can create dictionaries using dictionary comprehensions, which are similar to list comprehensions.

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

    You can check if a key exists in a dictionary using the in keyword.

    print("name" in person)  # Output: True
    print("address" in person)  # Output: False