USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
د.إ
United Arab Emirates dirham
ر.س
Saudi Arabia Riyal

Dictionaries

Lesson 7/15 | Study Time: 25 Min

Dictionaries in Python


A dictionary in Python is a powerful and flexible data structure that stores data in the form of key–value pairs. Unlike lists and tuples where elements are accessed using their position or index, dictionaries allow you to access data using meaningful keys. This makes data retrieval fast, clear, and highly organized. A dictionary is an unordered, mutable, and dynamic collection, meaning you can add, update, and remove items even after creation. Keys in a dictionary must be unique and immutable types such as strings, integers, or tuples, while values can be anything, including lists, other dictionaries, or complex objects. Dictionaries are extremely useful when data needs to be labeled, named, or mapped to something specific. For example, storing student information, product details, employee records, or JSON-like data structures. Python dictionaries are implemented using hash tables, which provide fast lookup and insertion operations, making them ideal for real-world applications where performance matters.




Syntax of a Dictionary


A dictionary is created using curly braces with key-value pairs separated by a colon.
example = { key1: value1,

                     key2: value2 }

Keys must be unique. If the same key is used again, later value overrides the previous one. Values can be duplicated and can be of any type.


Examples of Dictionaries 

Example 1: Creating a Dictionary

student = {

    "name": "Mayank",

    "age": 20,

    "course": "BCA"

}

# Dictionary with keys: name, age, course and their values

print(student)


Example 2: Accessing Values Using Keys

student = {"name": "Mayank", "age": 20}

# Accessing value using its key

print(student["name"])  # Output: Mayank

print(student["age"])   # Output: 20


Example 3: Adding New Key–Value Pairs

student = {"name": "Mayank", "age": 20}

# Adding new key-value pair

student["city"] = "Noida"

print(student)  

# Output: {'name': 'Mayank', 'age': 20, 'city': 'Noida'}


Example 4: Updating Values

student = {"name": "Mayank", "age": 20}

# Updating the value of the key 'age'

student["age"] = 21

print(student)  

# Output: {'name': 'Mayank', 'age': 21}


Example 5: Removing Items

info = {"brand": "Apple", "price": 50000}

# Using pop() to remove a key and return its value

removed_value = info.pop("price")

print(removed_value)     # Output: 50000

print(info)              # Output: {'brand': 'Apple'}


Example 6: Using get() to Safely Access Keys

student = {"name": "Mayank"}

# get() does not give an error if key is missing

print(student.get("age"))         # Output: None

print(student.get("age", "N/A"))  # Output: N/A


Example 7: Looping Through Dictionary

student = {"name": "Mayank", "age": 21, "course": "BCA"}

# Looping through keys

for key in student:

    print(key, student[key])  

    # Prints key and its value


Example 8: Nested Dictionaries

students = {

    "101": {"name": "Mayank", "age": 21},

    "102": {"name": "Riya", "age": 20}

}

# Accessing nested dictionary values

print(students["101"]["name"])  # Output: Mayank



Dictionary Methods


Dictionary methods in Python are built-in functions that help manage and manipulate key-value pairs efficiently. They allow you to add, update, access, and remove items in a dictionary with ease. Common methods include keys(), values(), items(), get(), update(), pop(), and clear(). These methods make data handling faster and reduce the complexity of operations on dictionaries. Understanding dictionary methods is essential for effective and organized data management in Python programs.

1. Get() Method


The get() method retrieves the value of a specified key from the dictionary. Unlike direct key access, get() does not raise an error if the key is missing. Instead, it returns None or a default value provided by the programmer. This method is safe and avoids crashes due to missing keys.


Syntax

dictionary_name.get(key, default_value)


Example

student = {"name": "Aman", "age": 20}


print(student.get("name"))       # Output: Aman

print(student.get("marks"))      # Key not present → Output: None

print(student.get("marks", 0))   # Returns default value → Output: 0



2. Keys() Method


The keys() method in Python returns all the keys of a dictionary as a dynamic view object that updates automatically when the dictionary changes. It allows easy access to all keys without creating a separate list. This method is useful for iterating over keys or checking the presence of specific keys. It helps in managing and organizing data efficiently in dictionaries. Understanding keys() is essential for effective dictionary operations in Python.


Syntax

dictionary_name.keys()


Example

info = {"id": 101, "name": "Riya"}


print(info.keys())               # Output: dict_keys(['id', 'name'])


3. Values() Method


The values() method in Python returns all the values stored in a dictionary as a dynamic view object. This view updates automatically whenever the dictionary is modified, such as when values are added, changed, or removed. It allows easy access to all dictionary values without creating a separate list. The method is useful for iterating over values or performing operations on them. Understanding values() helps in efficient data handling and manipulation in Python dictionaries.


Syntax

dictionary_name.values()


Example

data = {"a": 1, "b": 2}


print(data.values())             # Output: dict_values([1, 2])


4. Items() Method


The items() method in Python returns all key-value pairs of a dictionary as tuples within a dynamic view object. This view updates automatically when the dictionary changes. It is especially useful for looping through dictionaries, as it allows simultaneous access to both keys and values. The method simplifies operations like searching, updating, or displaying dictionary data. Understanding items() is important for efficient and organized dictionary handling in Python.


Syntax

dictionary_name.items()


Example

student = {"name": "Aman", "age": 20}


print(student.items())           # Output: dict_items([('name', 'Aman'), ('age', 20)])


5. Update() Method


The update() method in Python adds new key-value pairs to a dictionary or updates the values of existing keys. If a key already exists, its value is overwritten; if it does not exist, a new key-value pair is added. This method is commonly used to merge dictionaries efficiently. It helps in maintaining and modifying dictionary data without manually checking for existing keys. Understanding update() is essential for dynamic and flexible dictionary operations in Python.


Syntax

dictionary_name.update(new_dictionary)


Example

user = {"name": "Riya", "age": 21}

user.update({"age": 22, "city": "Delhi"})


print(user)                      # Output: {'name': 'Riya', 'age': 22, 'city': 'Delhi'}


6. Pop() Method


The pop() method in Python removes a key-value pair from a dictionary using the specified key and returns its corresponding value. If the key does not exist and no default value is provided, it raises a KeyError. This method is useful for extracting and deleting items simultaneously. It helps manage dictionary data efficiently while handling missing keys safely. Understanding pop() is important for dynamic and controlled dictionary operations in Python.


Syntax

dictionary_name.pop(key, default_value)


Example

info = {"a": 10, "b": 20}


print(info.pop("a"))             # Removes key 'a' → Output: 10

print(info)                      # Output: {'b': 20}


7. Popitem() Method


The popitem() method in Python removes and returns the last inserted key-value pair from a dictionary as a tuple. It is useful when the order of insertion matters, such as implementing stacks or accessing the most recently added items. This method allows efficient removal of the latest entry without specifying a key. It simplifies operations where the last added data needs to be retrieved and deleted. Understanding popitem() helps in managing dictionary data effectively.


Syntax

dictionary_name.popitem()


Example

data = {"x": 1, "y": 2}


print(data.popitem())            # Output: ('y', 2)

print(data)                      # Output: {'x': 1}


8. Clear() Method


The clear() method in Python removes all key-value pairs from a dictionary, leaving it empty. The dictionary variable itself still exists, but its contents are completely deleted. This method is useful when you need to reset a dictionary without deleting the variable. It simplifies clearing data efficiently in a single step. Understanding clear() helps in managing and reusing dictionary variables effectively.


Syntax

dictionary_name.clear()


Example

user = {"name": "Aman", "age": 20}

user.clear()


print(user)                   


9. Copy() Method


The copy() method in Python creates a shallow copy of a dictionary, duplicating its top-level keys and values. Nested objects within the dictionary are not deeply copied. This allows you to create a new dictionary that can be modified independently of the original. It is useful when you need a separate version of a dictionary without affecting the original data. Understanding copy() helps in safely managing and manipulating dictionary data.


Syntax

dictionary_name.copy()


Example

original = {"a": 1, "b": 2}

new_dict = original.copy()


print(new_dict)                  # Output: {'a': 1, 'b': 2}


10. Setdefault() Method


The setdefault() method in Python returns the value of a key if it exists in the dictionary. If the key does not exist, it adds the key with a specified default value and then returns that value. This method is useful for building dictionaries dynamically without checking for key existence manually. It simplifies code when initializing or updating dictionary entries. Understanding setdefault() helps in efficient and organized dictionary management.

Syntax

dictionary_name.setdefault(key, default_value)


Example

user = {"name": "Riya"}


print(user.setdefault("age", 18))   # Adds key 'age' with value 18 → Output: 18

print(user)                         # Output: {'name': 'Riya', 'age': 18}