0% found this document useful (0 votes)
27 views

Dictionary in Python

The document provides a comprehensive overview of dictionaries in Python, detailing their structure as collections of key-value pairs, and highlighting their unordered, mutable, and indexed nature. It covers various operations such as adding, updating, and deleting items, as well as built-in functions and methods for dictionary manipulation. Additionally, it explains the benefits of using dictionaries for efficient data retrieval and flexible data storage.

Uploaded by

Rida Shaikh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Dictionary in Python

The document provides a comprehensive overview of dictionaries in Python, detailing their structure as collections of key-value pairs, and highlighting their unordered, mutable, and indexed nature. It covers various operations such as adding, updating, and deleting items, as well as built-in functions and methods for dictionary manipulation. Additionally, it explains the benefits of using dictionaries for efficient data retrieval and flexible data storage.

Uploaded by

Rida Shaikh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Dictionary in Python

 Introduction to Dictionary
 Accessing values in dictionary.
 Updating dictionary.
 Deleting dictionary.
 Basic dictionary Operation.
 Build in dictionary functions.

Introduction to Dictionary in Python


 Python used 4 built-in data types to store collections of data like Tuple, List, Set, and
Dictionary. These all build in types has different qualities and usage.
 A dictionary is a data structure that allow you to store data in key value pairs.
 Keys are enclosed in quotation mark.
 Each key and values are separated by colon sign.
 All keys and values are enclosed in pair of curly brace.
 Dictionary followed by empty curly brace creates empty dictionary.
 When you create dictionary with dict(), then keys and values are separated by equal to
sign.
 You can create dictionary with list of tuples separated by comma.
 You can add, remove or update new key value pair once it is created.
Introduction to Python Dictionary
 A dictionary in Python is a built-in data structure that stores data in key-value pairs.
 It's an unordered, mutable, and indexed collection of elements where each key is associated
with a specific value.
 Dictionaries are optimized for fast lookups, allowing data retrieval in constant time, making
them one of the most useful and efficient data structures in Python.

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:

Subject: Mastering Python - Dictionary Print Date: [27/Oct/24], Page 2 of 7


Basic Operations on Dictionary
 Adding Items:
o You can add a new key-value pair to the dictionary.
 Updating Items:
o You can update the value associated with a specific key.
 Removing Items:
o You can remove the item with pop(), del keyword, popitem(), clear().
 Example:

Subject: Mastering Python - Dictionary Print Date: [27/Oct/24], Page 3 of 7


Accessing Values in a Dictionary
 Using Keys: You can access values using their respective keys:
 Using get():
o You can use the get() method to access values.
o It returns value if key is present.
o It returns None or specified default if key does not exist.

Subject: Mastering Python - Dictionary Print Date: [27/Oct/24], Page 4 of 7


Traversing a Dictionary
You can iterate over a dictionary using loops:
 Looping Through Keys:
 Looping Through Values:
 Looping Through Key-Value Pairs:

Subject: Mastering Python - Dictionary Print Date: [27/Oct/24], Page 5 of 7


Built-in Functions for Dictionary
 len(): Returns the number of items (key-value pairs) in a dictionary.
 str(): Converts the dictionary to a string representation.
 in: Checks if a key is present in the dictionary.
 dict(): Creates a new dictionary.
 Example:

Built-in Dictionary Methods


 keys(): Returns a view object with all the keys in the dictionary.
o Syntax: my_dict.keys()
 values(): Returns a view object with all the values in the dictionary.
o Syntax: my_dict.values()
 items(): Returns a view object containing the key-value pairs as tuples.
o Syntax: my_dict.items()
 get(): Returns the value for a specified key, or a default value if the key doesn't exist.
o Syntax: my_dict.get("age", 0)
 update(): Updates the dictionary with the key-value pairs from another dictionary or from an
iterable of key-value pairs.
o Syntax: my_dict.update({"name": "Bob", "age": 28})
 pop(): Removes and returns the value associated with a specific key.
Subject: Mastering Python - Dictionary Print Date: [27/Oct/24], Page 6 of 7
o Syntax: my_dict.pop("age")
 popitem(): Removes and returns the last inserted key-value pair.
o Syntax: my_dict.popitem()
 setdefault(): Returns the value of a key if it exists; otherwise, it sets the key with a default
value.
o Syntax: my_dict.setdefault("country", "USA")
 copy(): Returns a shallow copy of the dictionary.
o Syntax: new_dict = my_dict.copy()
 fromkeys(): Creates a new dictionary from the given keys and sets all values to the same
provided value.
o Syntax: new_dict = dict.fromkeys(["name", "age"], None)

Subject: Mastering Python - Dictionary Print Date: [27/Oct/24], Page 7 of 7

You might also like