Introduction to Dictionaries

Dictionary Data Structure

Dictionaries, also known as associative arrays or hash maps, are a data structure that stores a collection of key-value pairs. Each element in a dictionary consists of a unique key and its associated value. Dictionaries provide efficient look-up operations based on the keys.

In dictionaries, the keys are typically strings, numbers, or other immutable data types, while the values can be of any data type, including other dictionaries. The keys must be unique within a dictionary, and they are used to access and retrieve the associated values.

Implementation of Dictionary

Here's an example of a dictionary in Python:

my_dict = {

    "name": "John",

    "age": 25,

    "city": "New York"

}

In this example, my_dict is a dictionary that stores information about a person. The keys "name", "age", and "city" correspond to the attributes of the person, while the values "John", 25, and "New York" represent the actual data associated with each attribute.


You can access the values in a dictionary by specifying the corresponding key:

print(my_dict["name"])  # Output: John

print(my_dict["age"])  # Output: 25

print(my_dict["city"])  # Output: New York


You can also modify the values associated with keys or add new key-value pairs:

my_dict["age"] = 30  # Modify the value associated with the key "age"

my_dict["occupation"] = "Engineer"  # Add a new key-value pair


print(my_dict["age"])  # Output: 30

print(my_dict["occupation"])  # Output: Engineer


Dictionaries provide fast access to values based on keys, typically with an average-case time complexity of O(1). They are useful when you need to store and retrieve data in a flexible and efficient manner, especially when the order of elements is not important but quick look-up is necessary.