What Is Dictionary?
A dictionary is a data type in Python that stores data in a key-value pair format. It is also known as an associative array or hash map in other programming languages.
The key-value pairs within a dictionary are enclosed in curly brackets {} and separated by commas. The keys are unique, immutable objects, while the values can be of any data type.
Example of Dictionary Data Type:
To better understand the concept of dictionaries, let’s dive into an example. Suppose we want to store information about a student, such as their name, age, and grade. We can create a dictionary to hold this information as follows:
students = { "name": "John Doe", "age": 18, "grade": 12 }
In this example, the keys are “name”, “age”, and “grade”, while the corresponding values are “John Doe”, 18, and 12 respectively.
Accessing Dictionary Values:
We can access the values in a dictionary by using their corresponding keys. For example, to retrieve the student’s name from the above dictionary, we can use the following code:
name = students["name"] print(name) # Output: John Doe
Modifying Dictionary Values:
Dictionaries allow us to modify values associated with existing keys or add new key-value pairs. Let’s say we want to update the student’s grade from 12 to 11:
students["grade"] = 11 print(students) # Output: {'name': 'John Doe', 'age': 18, 'grade': 11}
Dictionary Methods:
Python provides various built-in methods to perform operations on dictionaries. Here are a few commonly used ones:
- keys(): Returns a list of all the keys in the dictionary.
- values(): Returns a list of all the values in the dictionary.
- items(): Returns a list of key-value pairs (as tuples) in the dictionary.
- get(key): Returns the value associated with the specified key. If the key is not found, it returns None or a default value provided as an argument.
Example:
# Using keys() method print(students.keys()) # Output: ['name', 'age', 'grade'] # Using values() method print(students.values()) # Output: ['John Doe', 18, 11] # Using items() method print(students.items()) # Output: [('name', 'John Doe'), ('age', 18), ('grade', 11)] # Using get() method age = students.get("age") print(age) # Output: 18 grade = students.get("grades", "N/A") print(grade) # Output: N/A
In conclusion,
The dictionary data type in Python is a powerful tool for storing and manipulating data in a key-value pair format. Its flexibility and efficiency make it invaluable for various programming tasks. By understanding how to create dictionaries, access their values, modify them, and utilize built-in methods, you can leverage this data structure to enhance your Python programs.