1. Home
python

Python Tutorials - Elevate Your Coding Skills with Comprehensive Tutorials

Discover Python tutorials covering everything from the basics to advanced topics. Whether you're new to programming or looking to level up your skills, our tutorials will guide you every step of the way

  • 201 Lessons
  • 33 Hours
right-top-arrow

Tutorial Playlist

200 Lessons
37

Dictionary in Python

Updated on 22/05/20244,447 Views

Introduction

In this tutorial, we delve deep into one of Python's most versatile data structures: the dictionary. Dictionary in Python is a foundational component for those upskilling in the field as it offers efficient key-value data storage, proving indispensable for data manipulation, storage, and retrieval tasks.

Overview

Dictionary in Python, termed "dict", stands out as dynamic collections of key-value pairs. With their ability to provide rapid and efficient data access, they become an inevitable tool, especially when dealing with voluminous data that needs a structured format for easy access and modification.

Creating a Dictionary

Code:

# Creating a dictionary using curly braces {}
student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

print(student)

Complexities for Creating a Dictionary

The complexities for creating a dictionary in Python depend on various factors, including the size of the dictionary, the hash function's efficiency, and the implementation details of the Python interpreter. Here are the general complexities:

Time Complexity:

Best Case: O(1) - When creating an empty dictionary or adding the first few elements.

Average Case: O(1) - Constant time for inserting a new key-value pair.

Worst Case: O(n) - In the worst case, when there are hash collisions or frequent resizing, insertion can become linear. Resizing involves rehashing and reinserting elements, which can take time proportional to the size of the dictionary.

Space Complexity:

O(n) - The space complexity for a dictionary depends on the number of key-value pairs it contains.

Changing and Adding Elements to a Dictionary

Changing Elements to a Dictionary

Code:

student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

# Changing the value of an existing key
student["age"] = 21
print(student)  # Output: {'name': 'Alice', 'age': 21, 'major': 'Computer Science'}

Adding Elements to a Dictionary

Code:

student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

# Changing the value of an existing key
student["age"] = 21
print(student)  # Output: {'name': 'Alice', 'age': 21, 'major': 'Computer Science'}

# Adding a new key-value pair
student["university"] = "ABC University"
print(student)  # Output: {'name': 'Alice', 'age': 21, 'major': 'Computer Science', 'university': 'ABC University'}

Accessing Elements of a Dictionary

Code:

student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

# Accessing values using keys
name = student["name"]
age = student["age"]
major = student["major"]

print("Name:", name)   # Output: Name: Alice
print("Age:", age)     # Output: Age: 20
print("Major:", major) # Output: Major: Computer Science

Nested Dictionary

Code:

# Creating a nested dictionary
student = {
    "name": "Alice",
    "age": 20,
    "contact": {
        "email": "alice@example.com",
        "phone": "123-456-7890"
    },
    "courses": {
        "math": 95,
        "history": 85,
        "english": 90
    }
}

# Accessing elements in the nested dictionary
email = student["contact"]["email"]
math_score = student["courses"]["math"]

print("Email:", email)       # Output: Email: alice@example.com
print("Math Score:", math_score)  # Output: Math Score: 95

Accessing an Element of a Nested Dictionary

Code:

# Nested dictionary
student = {
    "name": "Alice",
    "age": 20,
    "contact": {
        "email": "alice@example.com",
        "phone": "123-456-7890"
    },
    "courses": {
        "math": 95,
        "history": 85,
        "english": 90
    }
}

# Accessing a nested element
email = student["contact"]["email"]
math_score = student["courses"]["math"]

print("Email:", email)       # Output: Email: alice@example.com
print("Math Score:", math_score)  # Output: Math Score: 95

Deleting Elements Using Del Keyword

Code:

student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

# Deleting a key-value pair
del student["age"]

print(student)  # Output: {'name': 'Alice', 'major': 'Computer Science'}

Dictionary Methods

Code:

# Creating a dictionary
student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

# Accessing keys, values, and items
keys = student.keys()
values = student.values()
items = student.items()

print("Keys:", keys)     # Output: Keys: dict_keys(['name', 'age', 'major'])
print("Values:", values) # Output: Values: dict_values(['Alice', 20, 'Computer Science'])
print("Items:", items)   # Output: Items: dict_items([('name', 'Alice'), ('age', 20), ('major', 'Computer Science')])

# Getting a value by key, with a default value if the key is not present
age = student.get("age", "N/A")
gender = student.get("gender", "N/A")

print("Age:", age)       # Output: Age: 20
print("Gender:", gender) # Output: Gender: N/A

# Adding or updating a key-value pair
student["university"] = "ABC University"
print(student)           # Output: {'name': 'Alice', 'age': 20, 'major': 'Computer Science', 'university': 'ABC University'}

# Removing a key-value pair and returning its value
removed_major = student.pop("major")
print("Removed Major:", removed_major)  # Output: Removed Major: Computer Science

# Removing the last key-value pair and returning it as a tuple
last_item = student.popitem()
print("Last Item:", last_item)  # Output: Last Item: ('university', 'ABC University')

# Clearing all items from the dictionary
student.clear()
print(student)  # Output: {}

# Copying a dictionary
original_dict = {"a": 1, "b": 2}
copy_dict = original_dict.copy()
print(copy_dict)  # Output: {'a': 1, 'b': 2}

Iterating Dictionary

Iterating Through Keys:

Code:

student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

# Iterating through keys using a for loop
for key in student:
    print(key)
# Output:
# name
# age
# major

Iterating Through Values:

Code:

student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

# Iterating through values using a for loop
for value in student.values():
    print(value)
# Output:
# Alice
# 20
# Computer Science

Iterating With Key-Value Pairs (Items):

Code:

student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

# Iterating with key-value pairs using a for loop
for key, value in student.items():
    print(key, ":", value)
# Output:
# name : Alice
# age : 20
# major : Computer Science

Using keys() Method with for loop:

Code:

student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

# Iterating through keys using keys() method and a for loop
for key in student.keys():
    print(key)
# Output:
# name
# age
# major

Using values() Method with for loop:

Code:

student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

# Iterating through values using values() method and a for loop
for value in student.values():
    print(value)
# Output:
# Alice
# 20
# Computer Science

Using items() Method with for Loop:

Code:

student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}
# Iterating with key-value pairs using items() method and a for loop
for key, value in student.items():
    print(key, ":", value)
# Output:
# name : Alice
# age : 20
# major : Computer Science

Properties of Dictionary Keys

Dictionary keys in Python have certain properties that influence their behavior and usage. Here are some important properties of dictionary keys:

  • Immutable: Dictionary keys must be of an immutable data type. Immutable types include strings, numbers, and tuples (as long as the tuples contain only immutable elements).
  • Unique: Dictionary keys must be unique. If you try to use the same key multiple times, the later values will overwrite the earlier ones.
  • Hashable: Since dictionary keys are used to hash and retrieve values, they must be hashable. Immutable data types are hashable, allowing for efficient lookups.
  • Order (Python 3.7+): In Python 3.7 and later, dictionaries maintain the insertion order of keys. This behavior was later made part of the Python language specification, so you can rely on ordered dictionaries in newer versions.
  • Unordered (Python < 3.7): In Python versions prior to 3.7, dictionaries do not guarantee the order of keys. If you need ordered behavior, you should use collections.OrderedDict.
  • No Duplicates: As mentioned, keys must be unique. Trying to insert duplicate keys will overwrite the existing value associated with that key.
  • Changing Values: Dictionary values can be of any type, including mutable ones like lists. Keys, however, must remain immutable to maintain dictionary integrity.
  • Performance: Dictionary lookups are very efficient due to the underlying hash table implementation. However, excessive hash collisions can degrade performance.

Here's an example demonstrating some of these properties:

Code:

# Immutable keys
dict1 = {1: "one", "two": 2, (3, 4): "tuple_key"}
print(dict1)

# Unique keys
dict2 = {"name": "Alice", "age": 25, "name": "Bob"}
print(dict2)  # Output: {'name': 'Bob', 'age': 25}

# Unordered behavior (Python < 3.7)
dict3 = {"a": 1, "b": 2, "c": 3}
print(dict3)  # Output may not maintain order

Built-in Dictionary Functions

  • len() - Returns the number of key-value pairs in the dictionary.
  • clear() - Removes all key-value pairs from the dictionary.
  • copy() - Returns a shallow copy of the dictionary.
  • fromkeys(keys, value) - Creates a new dictionary with the specified keys and a common value.
  • get(key, default) - Returns the value associated with the key. In the case that the key is not found, this function will return the default value.
  • items() - Returns a view of key-value pairs in the dictionary as tuples.
  • keys() - Returns a view of keys in the dictionary.
  • values() - Returns a view of values in the dictionary.
  • pop(key, default) - Removes and returns the value associated with the key. When the key cannot be found, this returns the default value.
  • popitem() - Removes and returns the last key-value pair as a tuple.
  • setdefault(key, default) - Returns the value associated with the key. In the case that the key is not found, this sets the key with the provided default value and returns it.
  • update(other_dict) - Updates the dictionary with key-value pairs from another dictionary or iterable.
  • dict() - Creates a new dictionary from a sequence of key-value pairs, a dictionary, or keyword arguments.
  • keys_view() - Returns a dynamic view of keys.
  • values_view() - Returns a dynamic view of values.
  • items_view() - Returns a dynamic view of key-value pairs.
  • popitem() - Removes and returns an arbitrary key-value pair as a tuple.

Here's an example showcasing some of these functions and methods:

Code:

student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

print(len(student))          # Output: 3
print(student.get("age"))    # Output: 20
print(student.keys())        # Output: dict_keys(['name', 'age', 'major'])
print(student.values())      # Output: dict_values(['Alice', 20, 'Computer Science'])
print(student.items())       # Output: dict_items([('name', 'Alice'), ('age', 20), ('major', 'Computer Science')])

# Removing and returning a key-value pair
removed_item = student.popitem()
print(removed_item)         # Output: ('major', 'Computer Science')

# Updating the dictionary with new data
new_data = {"university": "ABC University", "age": 21}
student.update(new_data)
print(student)              # Output: {'name': 'Alice', 'age': 21, 'university': 'ABC University'}

Built-in Dictionary Methods

  • clear() - Removes all key-value pairs from the dictionary.
  • copy() - Returns a shallow copy of the dictionary.
  • fromkeys(keys, value) - Creates a new dictionary with the specified keys and a common value.
  • get(key, default) - Returns the value associated with the key. When the key cannot be found, this returns the default value.
  • items() - Returns a view of key-value pairs in the dictionary as tuples.
  • keys() - Returns a view of keys in the dictionary.
  • values() - Returns a view of values in the dictionary.
  • pop(key, default) - Removes and returns the value associated with the key. In the case that the key is not found, this returns the default value.
  • popitem() - Removes and returns an arbitrary key-value pair as a tuple.
  • setdefault(key, default) - Returns the value associated with the key. When the key cannot be found, this sets the key with the provided default value and returns it.
  • update(other_dict) - Updates the dictionary with key-value pairs from another dictionary or iterable.

Here's an example demonstrating how to use some of these built-in dictionary methods:

Code:

# Creating a dictionary
student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

# Using dictionary methods
print(student.keys())        # Output: dict_keys(['name', 'age', 'major'])
print(student.values())      # Output: dict_values(['Alice', 20, 'Computer Science'])
print(student.items())       # Output: dict_items([('name', 'Alice'), ('age', 20), ('major', 'Computer Science')])

# Removing and returning a key-value pair
removed_item = student.popitem()
print(removed_item)         # Output: ('major', 'Computer Science')

# Updating the dictionary with new data
new_data = {"university": "ABC University", "age": 21}
student.update(new_data)
print(student)              # Output: {'name': 'Alice', 'age': 21, 'university': 'ABC University'}

# Clearing the dictionary
student.clear()
print(student)              # Output: {}

Conclusion

Dictionaries in Python are undeniably a pivotal data structure, bridging the gap between data storage needs and efficiency. Their flexible nature, combined with Python's suite of methods tailored for them, ensures their broad application, from simple data manipulations to complex algorithm implementations. For those on the path to Python mastery, understanding dictionaries is paramount. Hungry for more? upGrad offers a variety of courses tailored to nourish your thirst for knowledge in Python.

FAQs

  1. Is a dictionary in Python mutable or immutable?

Dictionaries in Python are mutable, allowing modifications after their creation.

  1. What are some dictionary methods in Python?

Some common dictionary methods in Python include dict.keys(), dict.values(), and dict.update(). These enhance interactions with dictionaries.

  1. How do you loop through a dictionary in Python?

Utilize the for loop with dict.items() for efficient key-value pair iteration.

  1. How can you sort a dictionary by its values?

Employ the sorted() function and specify key=lambda x: x[1].

  1. How to retrieve all keys from a dictionary?

The method dict.keys() will fetch all keys present in the dictionary.

Pavan

PAVAN VADAPALLI

Director of Engineering

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working … Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...