What is a dictionary in Python?

A dictionary in Python is an unordered collection of data values, stored as key-value pairs. It is a mutable data type, which means that we can add, modify, or delete elements from a dictionary after it is created.

Dictionaries are often used to store data that needs to be organized and accessed efficiently, such as a database of employee records or a collection of user preferences. They are also commonly used to store data that is retrieved from a server or a web API, as the key-value pairs make it easy to access and manipulate specific pieces of information.

To create a dictionary in Python, we use curly braces {} and specify key-value pairs separated by a colon :. For example:

employee_records = {
    "John Smith": {
        "age": 35,
        "position": "Manager"
    },
    "Jane Doe": {
        "age": 29,
        "position": "Developer"
    }
}


In this example, we have created a dictionary called employee_records that contains two key-value pairs. The keys are strings ("John Smith" and "Jane Doe") and the values are dictionaries containing information about each employee's age and position.

To access the value associated with a particular key, we can use the square bracket notation, like this:

john_age = employee_records["John Smith"]["age"]


 This will assign the value 35 to the variable john_age.

We can also modify the values in a dictionary by assigning a new value to a key. For example:

employee_records["John Smith"]["position"] = "Director"


This will change John Smith's position from "Manager" to "Director".

We can also add new key-value pairs to a dictionary using the same square bracket notation:

employee_records["Bill Johnson"] = {
    "age": 40,
    "position": "Salesperson"
}


This will add a new key-value pair to the employee_records dictionary, with a key of "Bill Johnson" and a value of a dictionary containing his age and position.

Finally, we can delete key-value pairs from a dictionary using the del keyword:

del employee_records["Jane Doe"]


This will remove the key-value pair for "Jane Doe" from the employee_records dictionary.

Dictionaries are an essential data type in Python, and they provide a flexible and efficient way to store and access data. They are commonly used in a wide range of applications, from simple scripts to complex software systems.

 

 

 

No comments

Powered by Blogger.