Dictionary in Python
Dictionary in Python
Introduction to Dictionary
Accessing values in dictionary.
Updating dictionary.
Deleting dictionary.
Basic dictionary Operation.
Build in dictionary functions.
Features of a Dictionary
Unordered: Dictionary elements are not stored in a particular order.
Mutable: You can change, add, or remove elements after the dictionary is created.
Indexed by Keys: Instead of using numerical indices, dictionaries use unique keys to
access values.
Heterogeneous Data Types: Keys and values can be of any data type.
Subject: Mastering Python - Dictionary Print Date: [27/Oct/24], Page 1 of 7
Fast Lookups: Dictionary lookups and insertions are generally fast due to the hash table
implementation.
Benefits of a Dictionary
Efficient Data Retrieval: Using keys allows quick access to data.
Flexible Data Storage: Supports different types of data for both keys and values.
Dynamic Size: Grows and shrinks automatically as data is added or removed.
Useful for Real-World Mappings: Best suited for situations where data needs to be
mapped, like storing phone book data or a product price list.
Definition of a Dictionary
A dictionary is defined as a collection of key-value pairs where keys must be unique and are
used to access the associated values.
Syntax: my_dict = {key1: value1, key2: value2}
Initialization of a Dictionary
You can initialize a dictionary in different ways:
Empty Dictionary:
o empty_dict = {}
Dictionary With Values:
o my_dict = {"name": "Alice", "age": 25, "city": "New York"}
Using dict() Constructor:
o my_dict = dict(name="Alice", age=25, city="New York")
From a List of Tuples:
o my_dict = dict([('name', 'Alice'), ('age', 25), ('city', 'New York')])
Example: