Python Dictionaries

Mon May 13, 2024

A dictionary in Python is a versatile and fundamental data structure used for organizing and storing data in the form of key-value pairs. It is sometimes also referred to as a "dict." Dictionaries allow you to map keys to corresponding values, enabling efficient and flexible data retrieval and manipulation.

Key characteristics of dictionaries:
    Key-Value Structure:Dictionaries are composed of key-value pairs. Each key is unique within a dictionary and is used as a reference to access the associated value.
    Unordered:Dictionaries are unordered collections, which means that the order in which key-value pairs are stored may not be the same as the order in which they were added.
    Mutable:Dictionaries are mutable, meaning that you can add, modify, or remove key-value pairs after creating a dictionary. This makes them flexible for data management.
    Heterogeneous Data Types:Keys and values within a dictionary can be of different data types. You can use strings, numbers, or even other dictionaries as keys, and values can be of any data type, including lists, strings, numbers, or even functions.
    Creating a Dictionary
    Syntax:
    my_dict = {}
    Example:
    student = { 'name': 'John', 'age': 20, 'grade': 'A' }
    In this example, 'name', 'age', and 'grade' are keys, and 'John', 20, and 'A' are their respective values.
    How to access values in a dictionary:
    name = student['name']

    Modifying and Adding Items:Modifying Values:
    student['age'] = 21

    Adding New Items 
    student['major'] = 'Computer Science'

    Removing Items:
    major = student.pop('major')

Vijay Kashyap
Python in easy steps