277edb_Dictionaries and OOP in Python
277edb_Dictionaries and OOP in Python
in Python
Introduction to AI
Dictionary in Python
• A dictionary in Python is an unordered collection of data in the form
of key-value pairs. Dictionaries are optimized to retrieve values when
the key is known.
• dictionary_name = {
key1: value1,
key2: value2,
key3: value3
}
Creating a Dictionary
• we can create a dictionary using curly braces {} or the dict() constructor.
• Empty Dictionary:
You can create an empty dictionary using:
empty_dict = {}
Accessing Elements in a Dictionary
• Access a value by referring to its key:
• Use square brackets [] or the get() method to access values.
• The get() method is safer because it returns None if the key doesn’t
exist, whereas using square brackets will raise an error.
Adding, Updating, and Removing
Items in a Dictionary:
• You can add a new key-value pair or update an existing value by
assigning a value to a key.
• Use the del keyword or the pop() method to remove an item.
Iterating Through a Dictionary
• We can use a loop to iterate through the dictionary in different ways.
LIBRARY EXAMPLE:
Dictionary Methods
• keys(): Returns all the keys.
• values(): Returns all the values.
• items(): Returns all key-value pairs.
• update(): Updates the dictionary with key-value pairs from another
dictionary or iterable.
• pop(): Removes the specified key and returns the corresponding
value.
• clear(): Removes all items from the dictionary.
Dictionary Methods Example:
Nested Dictionaries
• A dictionary can contain another dictionary as a value.This is called a
nested dictionary.
• Example: